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

后端 未结 2 1250
别跟我提以往
别跟我提以往 2021-02-19 17:46

I have the following type being registered in Unity:

container.RegisterType, AzureTable>();

The

相关标签:
2条回答
  • 2021-02-19 18:15

    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")));
    
    0 讨论(0)
  • 2021-02-19 18:33

    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.

    0 讨论(0)
提交回复
热议问题