I have an architecture in which all the default dependencies are automatically injected through the Initialize and OnActionExecuting. This all works like a charm because, in runtime (not tests), the default controller activator will call these methods passing in the correct concrete objects. Fine.
My problem begins when I have a custom dependency not injectable in the Initialize and OnActionExecuting methods.
Exemple:
public class MyController
{
private IEmailSender emailSender = null;
}
Well.. in runtime emailSender will be null unless I set it to something else. In this case I would end up with something not so great, like this:
public class MyController
{
private IEmailSender emailSender = null;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
if(this.emailSender == null)
this.emailSender = new SomeConcreteEmailSender();
}
}
Ugly. I don’t want to do this “if null, instantiate” thing.
A more sofisticated way to inject IEmailSender would be creating my own ControllerActivator that would only be called in runtime (not tests) and would inject IEmailSender automatically without the need to do this “if”. But I don’t want to create a custom ControllerActivator for each controller that needs injection.
That being said, what is considered standard when it comes to custom dependency injection for ASP.NET controllers?
Constructor injection:
And here’s what’s considered as a poor-man’s-dependency-injection (please do not use) for people that do not wish to use an existing dependency injection framework (because for example they work in a company where some technically illiterate morons dictate what frameworks should be used and what not) or are too lazy to write a custom dependency resolver: