Question

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?

Was it helpful?

Solution

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>()));

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top