繁体   English   中英

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

这是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文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM