CodeGo.net> Unity.MVC无法解析我的控制器ctor与参数
作者:互联网
我有一个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文件.
标签:asp-net-web-api2,dependency-injection,unity-container,c,net 来源: https://codeday.me/bug/20191118/2027107.html