【问题标题】:Web API: ApiController creation with DIWeb API:使用 DI 创建 ApiController
【发布时间】:2012-07-12 10:16:22
【问题描述】:

我有一个带有参数化构造函数的 ApiController。 我读到框架可能使用依赖注入创建控制器。

所以我这样做了(就像这里解释的 http://code.google.com/p/autofac/wiki/MvcIntegration):

Global.asax

builder.RegisterControllers(Assembly.GetExecutingAssembly());
//or this
builder.RegisterType<ObjectsController>().InstancePerHttpRequest();

控制器如下所示:

public class ObjectsController : ApiController
    {
        IMyObject m_myObject = null;

        public ObjectsController(IMyObject obj)
        {
            m_myObject = obj;
        }
}

Global.asax 为了解决依赖关系,我使用了这个:

builder.Register<IMyObject >((c, p) =>
            {
                //... create object ...

                return obj;
            }).InstancePerHttpRequest();

但我收到此错误:

“ObjectsController”没有默认构造函数。

我认为我可以使用 DI 做到这一点

【问题讨论】:

标签: dependency-injection constructor controller asp.net-web-api


【解决方案1】:

如果您想在 ASP.NET Web API 中使用 DI,这个答案可以为您提供更好的解决方案: https://stackoverflow.com/a/10592456/538387

【讨论】:

    【解决方案2】:

    最常见的解决方案是使用 DI 特定的IDependencyResolver 实现。

    那篇文章给出了一个使用 Unity 的示例,但您应该能够相当轻松地使其与 AutoFac 一起使用。

    【讨论】:

      【解决方案3】:

      如果您使用 Unity,这就是您在 ASP.NET 4 Web API RC 中需要做的所有事情(截至 2013 年 8 月 8 日):

      添加对“Microsoft.Practices.Unity.dll”的引用[我在版本 3.0.0.0,通过 NuGet 添加] 添加对“Unity.WebApi.dll”的引用[我在版本 0.10.0.0,通过 NuGet 添加] 使用容器注册您的类型映射 - 类似于 Unity.WebApi 项目添加到您的项目中的 Bootstrapper.cs 中的代码。 在从 ApiController 类继承的控制器中,创建参数化构造函数,其参数类型为映射类型 瞧,您无需另一行代码即可将依赖项注入到构造函数中!

      【讨论】:

        【解决方案4】:

        正如其他人所建议的,使用任何 IDependencyResolver 实现似乎是个好主意。

        不幸的是,这并没有解决 WebAPI 在其基于 ApiController 的类中需要无参数构造器的问题。 => 我只是在我的 web api 控制器基类中使用属​​性注入而不是构造函数注入,并提供一个空的无参数构造函数。不漂亮但亲吻:-)

         public class ApiControllerBaseWithDependency : ApiController
        {
            [Microsoft.Practices.Unity.Dependency]
            protected MyServiceType Service { get; set;}
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-17
          • 2014-07-07
          • 1970-01-01
          • 1970-01-01
          • 2017-07-26
          • 2012-03-14
          • 1970-01-01
          • 2013-08-04
          相关资源
          最近更新 更多