本文介绍了在 Web API 中使用处理程序并让 Unity 解析每个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Unity 作为我的 IoC 框架,我正在根据处理程序中每个请求的标头中的值创建一个类型:

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);

问题在于处理程序的 SendAsync 意味着全局容器被不同的请求覆盖,并且在其构造函数中使用 IFoo 的控制器获得了错误的值.

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) 我可以使 SendAsync 同步吗?2) 如果不是,我如何为每个请求创建不同的实例并让 IoC 容器安全解析?

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-resolverhttp://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

提前致谢.

推荐答案

我同意 @Steven 的方法,但这并没有回答您关于如何解决每个请求的更普遍的问题.

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

我建议您更改为使用 UnityHierarchicalDependencyResolver,然后您在 HierarchicalLifetimeManager 中注册的任何内容都将根据请求进行解析.

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

改变这个...

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

这个...

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

这篇关于在 Web API 中使用处理程序并让 Unity 解析每个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 20:16