WebApi + Simple Injector + OWIN

我试图在WebAPI项目中使用SimpleInjector和OWIN。 但是, ConfigureAuth的以下行失败

 app.CreatePerOwinContext(container.GetInstance); 

例外情况是ApplicationUserManager注册为“Web API请求”生活方式,但实例是在Web API请求的上下文之外请求的。

我正在使用container.RegisterWebApiRequest(); 在容器初始化。 (如果我使用Register而不是RegisterWebApiRequest则不会有任何例外,但根据简单的注入器文档,这不是首选方法)

据我所知,需要使用CreatePerOwinContext注册ApplicationUserManager ,以便OWIN正常工作。 我想知道如果Simple Injector在启动期间无法解析实例,我们如何使用Simple Injector执行此操作。

我已经在这个SO答案中尝试过该方法,但它失败了同样的消息。

知道怎么解决这个问题?

我使用以下代码来解决此问题。

 public static void UseOwinContextInjector(this IAppBuilder app, Container container) { // Create an OWIN middleware to create an execution context scope app.Use(async (context, next) => { using (var scope = container.BeginExecutionContextScope()) { await next.Invoke(); } }); } 

然后调用app.UseOwinContextInjector(container); 注册依赖后立即。

感谢这篇文章

您可能会发现此问题很有用。 我们的想法是避免使用OWIN来解决依赖关系,因为它会给控制器代码带来一些混乱。 以下使用OWIN解析UserManager实例的代码是Service Locator反模式 :

 public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); } set { _userManager = value; } } 

而不是依靠OWIN来解决依赖关系,将所需的服务注入到控制器的构造函数中,并使用IDependencyResolver为您构建控制器。 本文演示如何在ASP.NET Web API中使用依赖项注入。