【问题标题】:WebApi + Simple Injector + OWINWebApi + 简单注入器 + OWIN
【发布时间】:2015-02-15 18:19:14
【问题描述】:

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

app.CreatePerOwinContext(container.GetInstance<ApplicationUserManager>);

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

我在容器初始化中使用container.RegisterWebApiRequest&lt;ApplicationUserManager&gt;();。 (如果我使用Register 而不是RegisterWebApiRequest,不会有任何例外,但这不是simple injector docs 的首选方法)

据我了解,ApplicationUserManager 需要使用CreatePerOwinContext 注册,OWIN 才能正常工作。我想知道我们如何使用 Simple Injector 来做到这一点,因为 Simple Injector 在启动期间无法解析实例。

我已经尝试过this SO answer 中的方法,但失败并显示相同的消息。

知道如何解决这个问题吗?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-identity owin simple-injector


    【解决方案1】:

    我使用以下代码解决了这个问题。

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

    感谢this post

    【讨论】:

    • 你有完整的例子可以看吗,我正在尝试做一些非常相似的事情,但我也在使用 IdentityServer3,一个处理程序,一个用于版本控制的属性。
    • 你能提供一个关于 Owin + MVC + SimpleInjector 的完整例子吗?
    【解决方案2】:

    您可能会发现this question 很有用。这个想法是避免使用 OWIN 来解决依赖关系,因为它会给您的控制器代码带来一些混乱。以下使用 OWIN 解析 UserManager 实例的代码是 Service Locator anti-pattern

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

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

    【讨论】:

    • 谢谢。我没有使用 OWIN 来解决依赖关系。 OWIN 在内部使用 ApplicationUserManager 并尝试从 OwinContext 获取此信息。因此,OWIN 必须知道 ApplicationUserManager 实例才能正常工作(如果我错了,请纠正我)。我没有使用您在 AccountController 中引用的代码。 AccountController 通过构造函数注入获取 ApplicationUserManager。所以问题依然存在。
    • @su8898 那么我建议你看看this blog post——也许你会在那里找到一些有用的代码示例。
    • 博文中的示例在 ConfigureAuth 中使用 app.CreatePerOwinContext(() =&gt; DependencyResolver.Current.GetService&lt;ApplicationUserManager&gt;());,因为它是一个 MVC 项目。 WebAPI 对 DependancyResolver 有不同的实现。即使我们使用这样的方法,我认为它也会失败,因为 SimpleInjector 将无法解析 ConfigureAuth 中的ApplicationUserManager。我想知道如何解决这个问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多