团结.MVC不能解析我的控制器变量与参数

本文关键字:控制器 变量 参数 我的 MVC 不能 团结 | 更新日期: 2023-09-27 18:02:05

我有一个ASP。MVC 4站点也有一个Web API 2控制器。我使用的是Unity。用于DI的MVC。当我从javascript调用API时,它说它不能创建控制器的实例。如果我创建一个默认的actor,它会创建实例,但当然依赖项是空的,但至少我知道那部分是工作的。

这是我的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>();
        }

我错过了什么?

团结.MVC不能解析我的控制器变量与参数

WebAPI控制器有一个单独的Unity注册。因为你已经在使用Unity了。MVC包中可以添加unity . asp.net . webapi引导程序。

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