How can I pass in constructor arguments when I register a type in Unity?

久未见 提交于 2019-12-09 14:36:54

问题


I have the following type being registered in Unity:

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>();

The definition and constructors for AzureTable are as follows:

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) { }

Can I specify the constructor arguments in the RegisterType line? I need to be able to pass in the tableName for example.

This is a follow-up to my last question. That question was I think answered but I didn't really clearly ask how to get the constructor arguments in.


回答1:


Here is an MSDN page describing what you require, Injecting Values. Take a look at using the InjectionConstructor class in your register type line. You will end up with a line like this:

container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(typeof(CloudStorageAccount)));

The constructor parameters to InjectionConstructor are the values to be passed to your AzureTable<Account>. Any typeof parameters leave unity to resolve the value to use. Otherwise you can just pass your implementation:

CloudStorageAccount account = new CloudStorageAccount();
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(account));

Or a named parameter:

container.RegisterType<CloudStorageAccount>("MyAccount");
container.RegisterType<IAzureTable<Account>, AzureTable<Account>>(new InjectionConstructor(new ResolvedParameter<CloudStorageAccount>("MyAccount")));



回答2:


You could give this a try:

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

More info from MSDN here.



来源:https://stackoverflow.com/questions/8614936/how-can-i-pass-in-constructor-arguments-when-i-register-a-type-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!