Autofac with Owin

2019-03-04 00:21发布

问题:

I have an issue with Autofac. The documentation clearly states that when using Web API 2 and OWIN you must not use GlobalConfiguration.Configuration anywhere:

A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.

which can be found here (at the bottom of the page): http://autofac.readthedocs.io/en/latest/integration/webapi.html

But no matter what I do, I can not get Autofac to work using:

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

instead of:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

When I use the latter, it works. Does anyone know why?

回答1:

Ok, I figured this out. I will post the answer here incase anyone else has this issue. As the documentation stated, you can't use GlobalConfiguration anywhere.... so I did a search and I found it somewhere else. I had this:

GlobalConfiguration.Configure(WebApiConfig.Register); 

which should have been:

WebApiConfig.Register(config); 

When I fixed that, I was able to use the proper

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);