3

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 asp.net 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?

4
  • The WebAPI controllers have a separate Unity registration. I see you are using Unity.MVC, there is also a Unity.AspNet.WebApi bootstrapper. Commented Aug 11, 2016 at 18:04
  • Ah I see. Interesting when I add that it also creates (so in this case overwrites) UnityConfig.cs. Do you know if I can mix the 2 inside 1 project? Commented Aug 11, 2016 at 18:08
  • You can have both. I think you'd have to save the file separately before you import the 2nd package then combine the two manually. Commented Aug 11, 2016 at 18:11
  • Yep that worked! Thank you much! Could you make this an answers so I can accept? Commented Aug 11, 2016 at 18:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.