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
382 views
in Technique[技术] by (71.8m points)

c# - using a Handler in Web API and having Unity resolve per request

I am using Unity as my IoC framework and I am creating a type based on the value in the header of each request in a handler:

var container = new UnityContainer();

container.RegisterType<IFoo,Foo>(new InjectionConstructor(valuefromHeader));

GlobalConfiguration.Configuration.DependencyResolver = 
    new Unity.WebApi.UnityDependencyResolver(container);

The problem is that the handler's SendAsync means that the global container is getting overwritten by different requests and the controllers that use IFoo in their constructor are getting the wrong values.

1) Can I make the SendAsync sync? 2) If not, how do I create different instances for each request and have the IoC container resolve safely?

I have looked at the following articles without success:

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/ http://benfoster.io/blog/per-request-dependencies-in-aspnet-web-api-using-structuremap

Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I agree with @Steven's approach, but that doesn't answer your more general question of how to resolve per request.

I would recommend you change to using the UnityHierarchicalDependencyResolver and then anything you register with HierarchicalLifetimeManager will be resolved per request.

Change this...

GlobalConfiguration.Configuration.DependencyResolver = 
    new Unity.WebApi.UnityDependencyResolver(container);

to this...

GlobalConfiguration.Configuration.DependencyResolver = 
    new Unity.WebApi.UnityHierarchicalDependencyResolver(container);

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

...