Reputation: 675
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;
}
Upvotes: 0
Views: 417
Reputation: 27871
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.
Upvotes: 2