0

I'm creating an ASP.NET Identity 2.1 WebAPI service. It allows for registration, logging in and authorizing authtokens. In the Owin startup class that I have created following this tutorial is the following code:

public class OwinStartup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);

        ConfigureWebApi(httpConfig);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        app.UseWebApi(httpConfig);
    }

    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(AppDbContext.Create);
        app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);

        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
    }

    private void ConfigureWebApi(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

Now, in the ConfigureOAuthTokenGeneration method, a DbContext and UserManager are created. My question: how do I access this dbContext and UserManager in a different class in my WepAPI project?

yesman
  • 7,165
  • 15
  • 52
  • 117

1 Answers1

1
AppDbContext context = HttpContext.Current.GetOwinContext().Get<AppDbContext>();
AppUserManager userManager = HttpContext.Current.GetOwinContext().Get<AppUserManager();

The same way the AccountController (in the sample project) retrieves these values.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • Thanks. For some reason, this did not work for me before, but I guess I had to rebuild my project. – yesman Mar 27 '15 at 13:27