2个构造函数的依赖注入

时间:2014-02-24 13:14:30

标签: c#-4.0 dependency-injection unity-container

是否可以在具有2个构造函数的类中使用依赖注入?

例如,假设我有下一个界面:

    public interface ILogger
    {
        void Log(LogLevel level, string message, string CallerID);
    }

它的实施:

internal class NLogger : ILogger
{
    private static NLog.Logger _logger;

    public NLogger()
    {
        _logger = LogManager.GetCurrentClassLogger();
    }

    public NLogger(ISomeService srv): this()
    {
        srv.doSomthing();
    }

    public void Log(LogLevel level, string message, string CallerID)
    {
        //implementation
    }
}

我想注入ISomeService以防它存在于我的DI容器中并且如果它不存在 - 使用空构造函数并继续工作而不使用ISomeService

有可能吗?如果没有,你有建议如何实现类似的东西?

2 个答案:

答案 0 :(得分:1)

通常,大多数IoC容器都会选择它能够满足的最贪婪的构造函数。这意味着如果您注册了ISomeService,它将选择该构造函数,否则它将回退到默认构造函数。

答案 1 :(得分:1)

默认情况下,

Unity将选择参数最多的构造函数。如果您希望在注册映射时使用某个构造函数,则可以使用InjectionConstructor。

// Using default constructor
this.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor());

// Using ISomeService constructor
this.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor(new ResolvedParameter<ISomeService>()));