【问题标题】:Unity.MVC can't resolve my controller ctor with parameterUnity.MVC 无法使用参数解析我的控制器 ctor
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2015-06-23
    • 2020-01-17
    • 2021-08-29
    • 2015-04-16
    • 2015-03-06
    • 1970-01-01
    相关资源
    最近更新 更多