Unity.MVC 无法使用参数解析我的控制器 ctor

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

我有一个 ASP.MVC 4 站点,它也有一个 Web API 2 控制器。我正在使用 Unity.MVC 作为 DI。 当我从 javascript 调用 API 时,它说它无法创建控制器 的实例。如果我创建一个默认的 ctor,它会创建实例,但当然依赖项为 null,但至少我知道该部分正在工作。

这是我的 api 负责人:

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;
        }

这是 UnityConfig.cs 中的内容(这是我从 NuGet 获取它并填写依赖项时自动为我生成的)。当我启动应用程序时会调用它。

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

我错过了什么?

WebAPI 控制器有单独的 Unity 注册。由于您已经在使用 Unity.MVC 包,您可以添加 Unity.AspNet.WebApi 引导程序。

由于配置是自动替换的,我会在导入第二个包之前保存 UnityConfig.cs 的内容,然后手动将两者组合起来。但真正的区别在于单独的 Unity*Activator.cs 文件。