开发者

C# Unity container Ctor injection

开发者 https://www.devze.com 2023-04-12 18:03 出处:网络
Say we have: class A { ILogger myLog; A(ILogger log) { this.myLog = log; } 开发者_如何学运维... } And we have registered the ILogger interface before in the unity container, e.g.

Say we have:

class A
{
   ILogger myLog;
   A(ILogger log)
   {
      this.myLog = log;
   }
 开发者_如何学运维...
}

And we have registered the ILogger interface before in the unity container, e.g.

 container.RegisterType<ILogger, SomeLogger>();

And here the SomeLogger class:

class SomeLogger : ILogger
{
   string myString;
   SomeLogger(string test)
   {
     myString = test;
   }
 ...
}

Now, how can unity create an instance of SomeLogger for class A without passing a string to the ctor of SomeLogger? Suppose there is no other ctor for SomeLogger. Where can one specify the parameter(s) for ctor of the mapped SomeLogger type?


You can do that in your configuration:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
    </configSections>
    <unity>
        <containers>
            <container>
                <types>
                    <type type="[Namespace].ILogger, [AssemblyName]" mapTo="[Namespace].SomeLogger, [AssemblyName]">
                        <constructor>
                            <param name="test">
                                <value value="MyDesiredValue" />
                            </param>
                        </constructor>
                    </type>
                </types>
            </container>
        </containers>
  </unity>
</configuration>

This also declaratively registers your type, so the

container.RegisterType<ILogger, SomeLogger>();

call is no longer necessary.

-Doug


You can do this:

container.RegisterType<ILogger, SomeLogger>(new InjectionConstructor("myStringValue"));


you could also do this in the registration code as follows:

UnityContainer.RegisterType<ILogger, SomeLogger>();
UnityContainer.Configure<InjectedMembers>()
              .ConfigureInjectionFor<SomeLogger>(new InjectionConstructor("TestString"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号