1

I had a webapi in which I was using app.CreatePerOwinContext in startup.cs file but I want to migrate that webapi to .net core 2.1. So I have stuck at this point as I can't fine any alternate for CreatePerOwinContext.

Here is my webapi code:

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

So how can I convert the above code in .net core 2.1?

Ask
  • 3,076
  • 6
  • 30
  • 63

1 Answers1

1

That method was used as a service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern, and is not recommended for use in the vast majority of real world situations.

Instead, people use IOC containers now to manage their dependency injection. In ASP.NET MVC Core, there's now a lightweight and "good enough" IOC container provided for you as part of the framework.

Microsoft provides an overview in this article, but the short version is that in your Startup.cs you register your dependency tree under ConfigureServices (usually using an extension method so Startup.cs doesn't get too large).

After you've registered your dependencies, you load them either through property injection, constructor injection, or method parameter injection. This results in cleaner code that is more maintainable than standard service location.

Edit:

If you truly insist on managing a service locator either because the technical debt is acceptable or because the business case warrants the current design, then I suggest you transition your work from OwinContext over to HttpContext.

In ASP.NET Core, you access the HttpContext by injecting the HttpContextAccessor into your class, and changing your OwinContext calls to pull from the key value store in HttpContext.

Instructions for injecting HttpContextAccessor can be found in this SO answer. Simply store KVPs using HttpContext.Current.Application["myObject"].

I don't recommend doing this, but I'm willing to share it because I understand the reality of deadlines vs the idealism of architecture.

Jim Yarbro
  • 2,063
  • 15
  • 21
  • thanks for your answer but can you provide some sample code that how I can convert OwinContext to HttpContext? And how can I store in HttpContext.Current.Application["myObject"].? – Ask Aug 16 '18 at 05:20
  • @Ask Yeah man, it's pretty much right there in my answer. Check the link in my answer for the injected `HttpContextAccessor` and then simply use the Application KVP store using the syntax I used. – Jim Yarbro Aug 16 '18 at 06:25