WebApi + Simple Injector + OWIN

13

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

app.CreatePerOwinContext(container.GetInstance<ApplicationUserManager>);
The ApplicationUserManager is registered as 'Web API Request' lifestyle, but the instance is requested outside the context of a Web API Request. 我使用container.RegisterWebApiRequest<ApplicationUserManager>();在容器初始化中。(如果我使用Register而不是RegisterWebApiRequest,就不会出现任何异常。但是根据simple injector的文档,这不是首选方法。)
据我所知,为了使OWIN正常工作,需要使用CreatePerOwinContext注册ApplicationUserManager。 我想知道,在Simple Injector中如何实现这一点,因为Simple Injector无法在启动期间解析实例。
我已经尝试过此SO答案中的方法,但它返回相同的消息。 有什么想法可以解决这个问题吗?
2个回答

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

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

感谢这篇文章


4
你有完整的示例代码可以提供吗?我正在尝试做类似的事情,但我也在使用IdentityServer3、处理程序和版本控制的属性。 - OutOFTouch
你能提供一个关于Owin + MVC + SimpleInjector的完整示例吗? - Jerome2606

2
您可能会发现这个问题很有用。其思想是避免使用OWIN来解决依赖关系,因为它会在控制器代码中引入一些混乱。以下使用OWIN解析UserManager实例的代码是服务定位器反模式
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();                
    }
    set
    {
        _userManager = value;
    }
}

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


1
谢谢。我不使用OWIN来解决依赖关系。OWIN内部使用ApplicationUserManager并尝试从OwinContext中获取它。因此,使OWIN意识到ApplicationUserManager实例是必要的,以使OWIN正常工作(如果我错了,请纠正我)。我没有使用您在AccountController中引用的代码。AccountController通过构造函数注入获取ApplicationUserManager。所以问题仍然存在。 - su8898
1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Sergey Kolodiy
博客文章中的示例在 ConfigureAuth 中使用 app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());,因为它是一个 MVC 项目。WebAPI 对 DependancyResolver 有不同的实现。即使我们使用这样的方法,我认为它也会失败,因为 SimpleInjector 将无法在 ConfigureAuth 中解析 ApplicationUserManager。我想知道如何解决这个问题! - su8898

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接