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

时间:2011-12-23 10:28:31

标签: c# asp.net-mvc unity-container

我在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作为示例。

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

2 个答案:

答案 0 :(得分:29)

以下是描述您需要的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")));

答案 1 :(得分:4)

你可以尝试一下:

// 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.
  );

来自MSDN here的更多信息。