【发布时间】:2016-08-11 17:48:00
【问题描述】:
我有一个 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 时。你知道我是否可以混合 2 inside 1 项目吗?
-
你可以同时拥有。我认为您必须在导入第二个包之前单独保存文件,然后手动合并两者。
-
是的,成功了!非常感谢!你能把这个作为答案让我接受吗?
标签: c# .net dependency-injection asp.net-web-api2 unity-container