0

i'm in the process of upgrading an ASP.NET MVC 2 application to ASP.NET MVC 3. One of the improvements in version 3 i have read about is with dependency injection and the in-built service locator. So far my understanding is that i can remove my implentation of the controller factory and instead implement the IDependencyResolver interface. Now all i have to do is change the following in my Application_Start method:

var container = new UnityContainer();
...
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));

to:

var container = new UnityContainer();
...
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

So far so good, but i've seen reports that i also need to implement IControllerActivator. The examples i have seen simply shows how this uses the dependency resolver so i can't see why the default implementation doesn't do this automatically. If someone could explain this that would be great. I'm guessing i need to implement this interface to get constructor injection within my controllers. But how would i inject a dependency within say an action filter. Before i would have said:

var authorizationService = ServiceLocator.Current.GetInstance<IAuthorizationService>();

I know i could probably switch this out to use the new DependencyResolver but i thought that with ASP.NET MVC 3 it would allow me to tidy this up otherwise i don't see how the DependencyResolver is any different from the ServiceLocator.

I'd appreciate if you could help clarify a few of my issues as i like to understand something fully before i go ahead and implement it.

Thanks

nfplee
  • 7,643
  • 12
  • 63
  • 124
  • This may answer your questions: http://stackoverflow.com/questions/5653783/is-idependencyresolver-an-anti-pattern/5654204#5654204 – Mark Seemann Aug 24 '11 at 10:29

1 Answers1

0

You don't need to implement IControllerActivator for supporting constructor injection - its ability you get by using any 'good' IoC-container, for instance Ninject.

Please see example: source code 'Part I\10 - Overview of MVC Projects\10 - Overview of MVC Projects\2. Consolidating DI'' for book 'Pro ASP.NET MVC 3 Framework'.

For me no doubt it'll work with Unity too.

vladimir
  • 13,428
  • 2
  • 44
  • 70
  • Cheers i also found the following article which helps http://www.devtrends.co.uk/blog/do-not-implement-icontrolleractivator-in-asp.net-mvc-3. – nfplee Aug 25 '11 at 12:50