【问题标题】:Autofac with Web API 2.2带有 Web API 2.2 的 Autofac
【发布时间】:2015-07-05 04:52:50
【问题描述】:

在 global.asax.cs 中的简单测试注册:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        //AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //This allows interfaces etc to be provided as parameters to action methods
        ModelBinders.Binders.DefaultBinder = new DiModelBinder();

        //Now call the method to initialise anything that is required before startup (which includes setting up DI)
        WebUiInitialise.InitialiseThis(this);


        var builder = new Autofac.ContainerBuilder();
        builder.RegisterApiControllers(System.Reflection.Assembly.GetExecutingAssembly());
        builder.RegisterModule(new ServiceLayer.Startup.ServiceLayerModule());

        var container = builder.Build();
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
}

测试 apicontroller:

public class TestController : ApiController
{
    public TestController(IListService service)
    {
    }
    [HttpGet]
    public IQueryable<AspNetUser> Users(IListService service)
    {
        return null;
        //return service.GetAll<AspNetUser>();
    }
}

调试到TestController构造函数时,IListService服务有值,但调试到Users HttpGet方法时为null。

有没有办法解决 Web Api 控制器、get 和 post 方法的依赖关系(IListService 服务),而不仅仅是构造函数?

对于 MVC 控制器,方法解析,而不仅仅是构造函数。

【问题讨论】:

  • 您的实际问题是什么?
  • 你可以试试这样注册类型吗 - builder.RegisterType&lt;ServiceLayer.Startup.ServiceLayerModule&gt;().As&lt;IListService&gt;();
  • Autofac 似乎不适用于 apicontroller 方法用户。调试到该方法时未解析 IListService 服务。我试过 builder.RegisterType().As();那没有用。

标签: asp.net-web-api autofac


【解决方案1】:

如果您希望 Autofac 将某些内容注入您的 Web API 控制器,则它需要是构造函数参数或公共可设置属性。

即使在 MVC 中,Autofac 默认情况下也不会填充控制器操作参数。如果您还将特殊的 Autofac 操作调用程序注册到管道中,它具有一定的能力,但同样,这不是默认行为的一部分 - 它是可选的。

Web API 集成中不存在该操作调用程序支持。对于 Web API,您需要改用标准 IoC 实践。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多