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?
-
2Having multiple constructors is an anti-pattern. Please don't do that.Steven– Steven2014年02月24日 13:36:49 +00:00Commented Feb 24, 2014 at 13:36
2 Answers 2
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>()));
Comments
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.
3 Comments
ISomeService registration and when I resolving ILogger I'm getting an exception[OptionalDependency] can solve my issue. I didn't know this feature. ThanksExplore related questions
See similar questions with these tags.