0

I am trying to do multiple dependency injection using Ninject. I have 3 classes, EmailHelper, ExceptionHelper and ReportHelper. ExceptionHelper class requires EmailHelper and ReportHelper requires ExceptionHelper. Here is my code.

IKernel _kernel = new StandardKernel();
_kernel.Load(Assembly.GetExecutingAssembly());

IEmailHelper _emailHelper = _kernel.Get<IEmailHelper>(); 

ExceptionHelper exceptionHelper = new ExceptionHelper(_emailHelper);
ReportHelper reportHelper       = new ReportHelper(exceptionHelper);

ExceptionHelper and IEmailHelper seems loosely coupled, but ReportHelper and ExceptionHelper are still tightly coupled.

How can I make ReportHelper and ExceptionHelper loosely coupled?

Can I modify my code like this ?

IExceptionHelper _exceptionHelper = _kernel.Get<IExceptionHelper>();
ReportHelper reportHelper = new ReportHelper(_exceptionHelper);

But IExceptionHelper is not initiated with IEmailHelper? I am confused.

[edited]

Here is my ExceptionHelper constructor. Rest constructor has same structure.

private IEmailHelper _emailHelper;
public ExceptionHelper(IEmailHelper eh)
{
    _emailHelper = eh;
}
3
  • 1
    Create corresponding interfaces for each. Commented Nov 2, 2015 at 14:35
  • @DavidL I already made interfaces for each class. Commented Nov 2, 2015 at 14:43
  • Can you include the constructors of those classes in your question? Commented Nov 2, 2015 at 15:20

1 Answer 1

2

The constructors of your classes should look like something like this:

public ExceptionHelper(IEmailHelper email_helper)
{
    m_EmailHelper = email_helper;
}

public ReportHelper(IExceptionHelper exception_helper)
{
    m_ExceptionHelper = exception_helper;
}

Then you need to make sure that all of your types are registered with the container like this (or use other automatic ways of registration):

kernel.Bind<IReportHelper>().To<ReportHelper>();
kernel.Bind<IExceptionHelper>().To<ExceptionHelper>();
kernel.Bind<IEmailHelper>().To<EmailHelper>();

Then you can build a IReportHelper instance like this:

IReportHelper report_helper = kernel.Get<IReportHelper>();

And the container will manage the wiring automatically.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand IReportHelper report_helper = kernel.Get<IReportHelper>() this part. I don't need to pass IExceptionHelper instance as parameter?
Yes. The DI container will detect that the constructor of ReportHelper requires a IExceptionHelper dependency and it will be able to inject it. This is called Auto Wiring.

Your Answer

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.