在Unity中注册类型时,如何传递构造函数参数?

我在Unity中注册了以下类型:

container.RegisterType<IAzureTable, AzureTable>(); 

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

 public class AzureTable : AzureTableBase, 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作为示例。

这是我上一个问题的后续行动。 那个问题我想回答但是我并没有真正明白如何获取构造函数参数。

这是一个描述您需要的MSDN页面, 注入值 。 看一下在寄存器类型行中使用InjectionConstructor类。 你最终会得到一条这样的一条线:

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

InjectionConstructor的构造函数参数是要传递给AzureTable 。 任何类型的参数都会保持统一以解析要使用的值。 否则你可以通过你的实现:

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

或者命名参数:

 container.RegisterType("MyAccount"); container.RegisterType, AzureTable>(new InjectionConstructor(new ResolvedParameter("MyAccount"))); 

你可以尝试一下:

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

来自MSDN的更多信息。