Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

asp.net web api - MVC Web API not working with Autofac Integration

I used the MVC integration from autofac like this:

...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

But now I want to recreate the solution with the new Web Api RTM. And I want to use the new AutofacWebApiDependencyResolver class.

But if I do this with AutofacWebApiDependencyResolver i got this error:

The type Autofac.Integration.WebApi.AutofacWebApiDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.

I read that i have to do this now for setting the resolver:

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

But if I set it with '=', it is not set. Its still the DefaultResolver...

If I use the MVC AutofacDependencyResolver class again, it works.

Are were still problems with autofac and web api rtm? (the current integration is RC version)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ASP.Net Wep.API and ASP.NET MVC uses two different IDependencyResolver (because they designed the Wep.API to not depend on ASP.NET MVC) so you need to setup both:

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = 
     new AutofacWebApiDependencyResolver(container);

So the AutofacDependencyResolver is needed to inject decencies to regular MVC Controller derived controllers.

And the AutofacWebApiDependencyResolver is needed to inject dependencies to the Web.API ApiController derived controllers.

And don't forget to register your Api controllers in your container builder with the call (it differs from usual builder.RegisterControllers method):

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...