views:

388

answers:

3

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>();
        }
    }

}
+7  A: 

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 http://stackoverflow.com/questions/568137/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.

Yann Schwartz
I agree. You should only use your type resolver at the root of your application. If for no other reason than if you need to change injectors you don't have to change all your code, only the point at which your first object. In my application the only place that knows about the injector is Global.asax, and even there I'm using in 1 too many places (that, is I"m using it in 2 places). With constructor injection everything just falls into place and your object are insulated from it all.
Talljoe
I'm actually using Castle Windsor but with set of wrapper interfaces to hide its complexity/dependency.
Daniel A. White
Thank you for your help!
Daniel A. White
A: 

I'm assuming that the protected interfaces you have are dependencies for the controller. Its possible to set up an IoC container to inject the dependencies for you. It can certainly be done with Castle Windsor. You would need to change you BaseController class to have a constructor with the required dependencies, as long as the IoC container knows about the other services it'll be able to inject them.

Darren
A: 

One of the principles behind Inversion of Control and Component-Driven Development is about using static service locators only when there is no other way (i.e.: in web service hosts or object data sources).

Technically speaking, using static service locators the base controller does not violate IoC, it just does not use it.

Check out existing integration between Autofac IoC container and ASP.NET MVC (other containers should be able to do that as well).

Rinat Abdullin