WebApi + Simple Injector + OWIN

su8*_*898 13 c# simple-injector asp.net-web-api owin asp.net-identity

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

app.CreatePerOwinContext(container.GetInstance<ApplicationUserManager>);
Run Code Online (Sandbox Code Playgroud)

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

container.RegisterWebApiRequest<ApplicationUserManager>();在容器初始化中使用.(如果我使用Register而不是任何例外,RegisterWebApiRequest但根据简单的注射器文档,这不是首选方法)

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

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

知道我怎么解决这个问题?

su8*_*898 13

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

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();
     }
});
}
Run Code Online (Sandbox Code Playgroud)

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

感谢这篇文章

  • 你有一个完整的例子可以看看,我正在尝试做一些非常相似的事情,但我也在使用IdentityServer3,一个处理程序和版本化的属性. (4认同)