1
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 

The function of the above code is to let the Container to manage the Controller instances. When a web request comes to the server, the server will get a Controller instance from the Container to handler the request.

But without Container, the server will automaticlly create a Controller instance.

What is the advantage of the management of Controller in Container? Thank you.

tereško
  • 58,060
  • 25
  • 98
  • 150
Robin Sun
  • 1,352
  • 3
  • 20
  • 45

1 Answers1

1

The advantage is that you can store all of your IoC type-registrations in a single container, and therefore manage their dependencies cleanly with the IoC container of your choice (Autofac, Windsor, Unity, Ninject, etc.). If your controllers have dependencies, this lets you avoid service-locating them within its methods.

I gave an usage example here for Unity. I am using Autofac for my own project but following the same pattern.

Community
  • 1
  • 1
agartee
  • 445
  • 2
  • 15
  • So you mean it like this: If we let Unity to handle the Controller, in a controller, we just only write `private UserService _userService; public UserController(UserService service){ _userService = service; }` If we let the MVC Framework to handle the instance creation of Controller, we need to write `private UserService _userService; public UserController(){ _userService = new UserService(); }` Is this all right? Is there any other advantage just like decoupling? – Robin Sun Aug 20 '13 at 05:39