.net core 2.1 中 CreatePerOwinContext 的替代项是什么

What is alternate for CreatePerOwinContext in .net core 2.1

我有一个 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中转换上面的代码呢?

该方法用作 service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern,不建议在绝大多数现实情况下使用。

相反,人们现在使用 IOC containers 来管理他们的依赖注入。在 ASP.NET MVC Core 中,现在有一个轻量级的 "good enough" IOC 容器作为框架的一部分为您提供。

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

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

编辑:

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

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

可以找到注入 HttpContextAccessor 的说明 。只需使用 HttpContext.Current.Application["myObject"].

存储 KVP

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