当我在Unity中注册一个类型时,我如何传递构造函数参数?
本文关键字:类型 构造函数 参数 一个 何传递 Unity 注册 | 更新日期: 2023-09-27 18:18:45
我在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.
);