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

Sam*_*tar 13 c# asp.net-mvc unity-container

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

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>();
Run Code Online (Sandbox Code Playgroud)

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) { }
Run Code Online (Sandbox Code Playgroud)

我可以在RegisterType行中指定构造函数参数吗?我需要能够传递tableName作为示例.

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

Luk*_*oid 30

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

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(typeof(CloudStorageAccount)));
Run Code Online (Sandbox Code Playgroud)

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

CloudStorageAccount account = new CloudStorageAccount();
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(account));
Run Code Online (Sandbox Code Playgroud)

或者命名参数:

container.RegisterType<CloudStorageAccount>("MyAccount");
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(new ResolvedParameter<CloudStorageAccount>("MyAccount")));
Run Code Online (Sandbox Code Playgroud)