user441521 user441521 - 2 months ago 11x
C# Question

Unity.MVC can't resolve my controller ctor with parameter

I have an ASP.MVC 4 site that also has a Web API 2 controller. I'm using Unity.MVC for DI. When I make the call to the API from javascript it's saying it can't create an instance of the controller. If I make a default ctor it creates the instance but of course the dependency is null then, but at least I know that part is working.

Here is my api ctor:

public class ContactController : ApiController
IContactService service;

// dependency injection is being done here by Unity. look in UnityConfig where we register IContactSevice to ContactService. Whenever see's IContactService it now knows to make a new ContactService instance
// we do this for 2 reasons: 1) this makes unit testing possible where we can mock the IContactService and 2) this makes maintaining the code easier where we can change the contact service class we want to use later and we wouldn't have to change the code here in this controller
public ContactController(IContactService _service)
service = _service;

Here is inside the UnityConfig.cs (that was auto generated for me when I got it from NuGet and I filled out the dependencies). This does get called when I start the app.

public static void RegisterTypes(IUnityContainer container)
container.RegisterType<IContactService, ContactService>();

What am I missing?


The WebAPI controllers have a separate Unity registration. Since you are already using the Unity.MVC package you can add the Unity.AspNet.WebApi bootstrapper.

Since the configuration is automatically replaced, I would save the contents of the UnityConfig.cs before importing the 2nd package then manually combine the two. But the real differences are in the separate Unity*Activator.cs files.