Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC and ASP.NET MVC Controllers

Should I do something along the lines of this? I'm thinking of all my controllers inheriting from BaseController. Does this break the design pattern of IoC? What else should I do instead?

public class BaseController: Controller
{
    protected ICookieService CookieService {
        get {
            return ServiceResolver.Resolve<ICookieService>(new { HttpContext = HttpContext });
        }
    }
    protected IDateTimeService DateTimeService { 
        get {
            return ServiceResolver.Resolve<IDateTimeService>();
        }
    }
    protected ISettingsService SettingsService {
        get {
            return ServiceResolver.Resolve<ISettingsService>();
        }
    }

}
like image 569
Daniel A. White Avatar asked Jun 05 '09 01:06

Daniel A. White


1 Answers

It would be a lot simpler to go with constructor injection and have a controllerfactory inject it for you. If you can, don't use a service locator (your ServiceResolver ) if you can get away with constructor injection.

There's some info on it on Adding a controller factory to ASP MVC

The link shows how to do it with StructureMap and it looks like you're using Unity, but it should be straightforward to adapt.

like image 174
Yann Schwartz Avatar answered Oct 26 '22 23:10

Yann Schwartz