我试图将Autofac用于带有WebApi2和OWIN的Asp.Net MVCApplication的DI容器。我的global.asax.cs在Application_Start()
中没有任何内容。我的startup.cs具有以下配置:
public void Configuration(IAppBuilder app)
{
DependencyInjectionConfig.Configure(app);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
AndpendencyInjectionConfig.Configure是:
public static void Configure(IAppBuilder app)
{
var config = new HttpConfiguration(); //this means webapi controllers don't use DI container
//var config = GlobalConfiguration.Configuration; //this makes MVC view controllers fail to do anything
var builder = new ContainerBuilder();
var assm = Assembly.GetExecutingAssembly();
//MVC and WebAPI Controllers
builder.RegisterControllers(assm);
builder.RegisterApiControllers(assm);
WebApiConfig.Register(config);
//Model Binders
builder.RegisterModelBinders(assm);
builder.RegisterModelBinderProvider();
//Modules
builder.RegisterModule<AutofacWebTypesModule>();
//MVC Views
builder.RegisterSource(new ViewRegistrationSource());
//MVC and WebAPI Filters
builder.RegisterFilterProvider();
builder.RegisterWebApiFilterProvider(config);
//Finally, Any custom registrations
RegisterComponents(builder, assm);
/* My items show in the builder as expected at this point */
//build the container
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
//Special OWIN bits
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
app.UseAutofacWebApi(config);
app.UseWebApi(config);
}
我的问题是,无论我使用var config = new HttpConfiguration();
还是var config = GlobalConfiguration.Configuration;
,Autofac似乎都不会进行任何参数分辨率。奖金,如果我使用GlobalConfiguration.Configuration
MVC控制器完全失败。
ApiController非常简单:
public class MessagesController : ApiController
{
private IMesageHandler MessageHandler {get; set;}
public MessagesController(IMessageHandler messageHandler)
{
this.MessageHandler = messageHandler;
}
[HttpGet]
public string Get()
{
return "Hello World";
}
}
例外是它无法找到无参数构造函数(因为Autofac容器似乎正在打盹)。