Ninject/DI: How to correctly pass initialisation data to injected type at runtime
Posted
by
MrLane
on Programmers
See other posts from Programmers
or by MrLane
Published on 2014-08-20T03:23:16Z
Indexed on
2014/08/20
4:29 UTC
Read the original article
Hit count: 271
dependency-injection
|ninject
I have the following two classes:
public class StoreService : IStoreService
{
private IEmailService _emailService;
public StoreService(IEmailService emailService)
{
_emailService = emailService;
}
}
public class EmailService : IEmailService
{
}
Using Ninject I can set up bindings no problem to get it to inject a concrete implementation of IEmailService into the StoreService constructor. StoreService is actually injected into the code behind of an ASP.NET WebForm as so:
[Ninject.Inject]
public IStoreService StoreService { get; set; }
But now I need to change EmailService to accept an object that contains SMTP related settings (that are pulled from the ApplicationSettings of the Web.config). So I changed EmailService to now look like this:
public class EmailService : IEmailService
{
private SMTPSettings _smtpSettings;
public void SetSMTPSettings(SMTPSettings smtpSettings)
{
_smtpSettings = smtpSettings;
}
}
Setting SMTPSettings in this way also requires it to be passed into StoreService (via another public method). This has to be done in the Page_Load method in the WebForms code behind (I only have access to the Settings class in the UI layer).
With manual/poor mans DI I could pass SMTPSettings directly into the constructor of EmailService and then inject EmailService into the StoreService constructor. With Ninject I don't have access to the instances of injected types outside of the objects they are injected to, so I have to set their data AFTER Ninject has already injected them via a separate public setter method. This to me seems wrong.
How should I really be solving this scenario?
© Programmers or respective owner