2011-12-23 78 views
10

我有以下类型被注册在Unity:是我在Unity中注册类型时如何传入构造函数参数?

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(); 

为AzureTable的定义和构造函数如下:

public class AzureTable<T> : AzureTableBase<T>, IInitializer where T : TableServiceEntity 
{ 

    public AzureTable() : this(CloudConfiguration.GetStorageAccount()) { } 
    public AzureTable(CloudStorageAccount account) : this(account, null) { } 
    public AzureTable(CloudStorageAccount account, string tableName) 
      : base(account, tableName) { } 

我可以在RegisterType行指定的构造函数参数?例如,我需要能够传入tableName。

这是我最后一个问题的后续工作。这个问题是我想回答,但我没有真正清楚如何获得构造函数参数。

回答

23

这是一个描述你需要什么的MSDN页面,Injecting Values。看看在你的注册类型行中使用InjectionConstructor类。您将结束与这样一行:

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(typeof(CloudStorageAccount))); 

构造函数参数InjectionConstructor是值传递到您的AzureTable<Account>。任何typeof参数都将统一以解决要使用的值。否则,你可以通过你实现:

CloudStorageAccount account = new CloudStorageAccount(); 
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(account)); 

或命名参数:

container.RegisterType<CloudStorageAccount>("MyAccount"); 
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(new ResolvedParameter<CloudStorageAccount>("MyAccount"))); 
+0

非常感谢您的帮助。这正是我需要的。 – 2011-12-23 10:49:07

4

你可以试试这个:从MSDN here

// Register your type: 
container.RegisterType<typeof(IAzureTable<Account>), typeof(AzureTable<Account>)>() 

// Then you can configure the constructor injection (also works for properties): 
container.Configure<InjectedMembers>() 
    .ConfigureInjectionFor<typeof(AzureTable<Account>>(
    new InjectionConstructor(myConstructorParam1, "my constructor parameter 2") // etc. 
); 

更多信息。

+0

非常感谢您的帮助。这正是我需要的。 – 2011-12-23 10:49:15

+0

没问题,我的荣幸。圣诞节快乐 :) – 2011-12-23 12:05:27

相关问题