我在 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 页面,描述了您的需求,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")));
关于c# - 在 Unity 中注册类型时如何传入构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614936/