繁体   English   中英

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

[英]How can I pass in constructor arguments when I register a type in 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。

这是我最后一个问题的跟进。 我认为已经回答了这个问题,但是我并没有真正明确地询问如何获取构造函数参数。

这是一个MSDN页面,其中描述了您所需的注入值 看看在您的寄存器类型行中使用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")));

您可以尝试一下:

// 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的更多信息在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM