AutoFac Web Api 2 集成问题

标签 autofac asp.net-web-api2

我刚刚将所有 Autofac 包更新到最新版本以获得对 web api 2 的支持。在我的 api Controller 中,我设置了一个构造函数,要求提供服务层类的实例,这与我将 autofac 与所有 mvc 一起使用的方式相同 Controller ,它工作正常。

在应用程序启动时执行的 ioc 配置中,我已经注册了 web api Controller 。

builder.RegisterType<UsersApiController>().InstancePerApiRequest();

我也试过
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

但是 autofac 不能与我的 api Controller 一起使用,请求注入(inject)服务类的构造函数甚至没有被执行。如果我没有在 api Controller 上包含默认参数少的构造函数,我也会收到错误消息。

web api 2 和 auto fac 是否存在已知问题,还是我遗漏了什么?

最佳答案

这个博客对我有用

http://danielhindrikes.se/cloud/azure/azure-mobile-services-and-autofac/

所以我的代码现在看起来是

public static void Register(){

            ConfigOptions options = new ConfigOptions();

            //Prepare Dependency Injection Container
            var configBuilder = new ConfigBuilder(options, DependencyInjectionConfig);


            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(configBuilder);
}

private static void DependencyInjectionConfig(ContainerBuilder containerBuilder)
{
            containerBuilder.Register(component => new EFProductRepository()).As<IProductRepository>().SingleInstance();
            containerBuilder.RegisterType<ProductsManager>().As<IProductsManager>();
}

关于AutoFac Web Api 2 集成问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077098/

相关文章:

asp.net-mvc-3 - 使用 Autofac 2.5 进行属性注入(inject)

model-view-controller - AutoFac 和 Log4Net - 注册和使用

c# - 其他项目中的 Web Api Controller ,路由属性不起作用

c# - 等待委托(delegate)中调用的任务

asp.net-web-api - 使用路由与查询字符串参数是错误的吗?

.net-core - .NET Core 默认依赖注入(inject)与 CaSTLe DynamicProxy

asp.net-mvc - 是否可以配置 Autofac 以与 ASP.NET MVC 和 ASP.NET Web Api 一起使用

c# - 运行时的 Autofac 绑定(bind)

c# - 加载 Microsoft.AspNet.WebApi.Client System.Net.Http.Formatting.dll 时尝试为 T4 文件查找 "missing dependency"