【问题标题】:What is alternate for CreatePerOwinContext in .net core 2.1.net core 2.1 中 CreatePerOwinContext 的替代方法是什么
【发布时间】:2019-01-22 00:05:14
【问题描述】:

我有一个 webapi,我在 startup.cs 文件中使用 app.CreatePerOwinContext,但我想将该 webapi 迁移到 .net core 2.1。所以我一直坚持这一点,因为我无法为 CreatePerOwinContext 提供任何替代方案。

这是我的 webapi 代码:

public static UserManager<IdentityUser> Create(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
    {
        var manager = new UserManager<IdentityUser>(new UserStore());
        return manager;
    }

 public void ConfigureAuth(IAppBuilder app)
    {

          app.CreatePerOwinContext<UserManager<IdentityUser>>(Create);
          ...
     }

那么如何在 .net core 2.1 中转换上面的代码呢?

【问题讨论】:

    标签: asp.net-web-api asp.net-core oauth-2.0 owin asp.net-core-2.0


    【解决方案1】:

    该方法用作service locator 来加载依赖项,然后在整个代码中访问它们。服务位置独立is considered an anti-pattern,不建议在绝大多数真实情况下使用。

    相反,人们现在使用IOC containers 来管理他们的依赖注入。在 ASP.NET MVC Core 中,现在作为框架的一部分为您提供了一个轻量级且“足够好”的 IOC 容器。

    Microsoft 提供了an overview in this article,但简短的版本是在您的 Startup.cs 中,您在 ConfigureServices 下注册您的依赖关系树(通常使用扩展方法,因此 Startup.cs 不会变得太大)。

    注册依赖项后,您可以通过属性注入、构造函数注入或方法参数注入来加载它们。这会产生比标准服务位置更易于维护的更简洁的代码。

    编辑:

    如果您真的坚持管理服务定位器是因为技术债务是可以接受的,或者是因为业务案例需要当前设计,那么我建议您将工作从 OwinContext 转移到 HttpContext。

    在 ASP.NET Core 中,您可以通过将 HttpContextAccessor 注入到您的类中来访问 HttpContext,并将 OwinContext 调用更改为从 HttpContext 中的键值存储中提取。

    可以在in this SO answer 找到注入 HttpContextAccessor 的说明。只需使用 HttpContext.Current.Application["myObject"] 存储 KVP。

    我不建议这样做,但我愿意分享它,因为我了解最后期限的现实与架构的理想主义。

    【讨论】:

    • 感谢您的回答,但您能否提供一些示例代码,说明如何将 OwinContext 转换为 HttpContext?以及如何存储在 HttpContext.Current.Application["myObject"].?
    • @Ask 是的,伙计,这几乎就在我的回答中。检查我的答案中注入的HttpContextAccessor 的链接,然后使用我使用的语法简单地使用应用程序 KVP 存储。
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多