문제

Is it possible to use Dependency Injection in a class which has 2 constructors?

for example, assume I have the next interface:

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

and it's implementation:

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

I want to inject ISomeService just in case it exists in my DI container and in case it doesn't exists - use the empty constructor and continue working without ISomeService.

Is it possible? if not, do you have a recommendation how to implement something similar?

도움이 되었습니까?

해결책

Unity by default will choose the constructor with the most parameters. If you want it to use a certain constructor when you're register the mapping, you can use InjectionConstructor.

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

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

다른 팁

Generally, most IoC containers will pick the most greedy constructor that it can satisfy. That means that if you have ISomeService registered, it will pick that constructor, otherwise it will fall back to the default constructor.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top