views:

59

answers:

1

Did something change in MVC 3? I have tried all the examples on the Internet for setting up Unity as my IoC Container, but I keep getting an error saying that Unity cannot resolve my UserController. Here is my constructor on my UserController:

public UserController(IUserService userService)
{
    _userService = userService;
}

I have the IUserService registered, that is not the problem. I keep getting errors, no matter what example I try. Does anyone have a good tutorial, or code, that works with Asp.Net MVC 3?

For reference, I have tried this, this, this, and this ... and tons of others.

Error:

The type UserController cannot be constructed.  You must configure the container to supply this value.

ErrorLine:

controller = MvcUnityContainer.Container.Resolve(controllerType) as IController;

Configuration:

MvcUnityContainer.Container = new UnityContainer().RegisterType<IUserService, UserService>();

ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
+1  A: 

To answer your question "What has changed in MVC3": MVC3 now has native support for dependency injection. Along with that change has come a redesign of the way controller objects are activated. Check out Brad Wilson's post (and the whole series about MVC 3.0) for more information:

http://bradwilson.typepad.com/blog/2010/10/service-location-pt10-controller-activator.html

Developers who previously implemented IControllerFactory by deriving from DefaultControllerFactory just to override the GetControllerInstance method for dependency injection purposes should now implement IControllerActivator instead.

In short, the unity controller factory (as well as the Ninject controller factory) are probably going to be broken until they release a new compatible version. A quick google did find this, however I have no idea if it works.

jslatts
Nothing I found worked, but thanks for the answer. I moved back to MVC 2.
Martin