1

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?

Steven
174k25 gold badges355 silver badges453 bronze badges
asked Feb 24, 2014 at 13:14
1
  • 2
    Having multiple constructors is an anti-pattern. Please don't do that. Commented Feb 24, 2014 at 13:36

2 Answers 2

1

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>()));
answered Feb 26, 2014 at 23:48
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Feb 24, 2014 at 13:21

3 Comments

I assumed this would be the case but I tried to remove ISomeService registration and when I resolving ILogger I'm getting an exception
@Ofir: That's because Unity is a 'group 2' container, as explained in this article. Group 2 is the most useless group to be in for a container.
Thanks, after I read your link I saw that [OptionalDependency] can solve my issue. I didn't know this feature. Thanks

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.