johnny 5
johnny 5

Reputation: 21033

Consume Dependencies from the Startup

I'm wondering what is the proper way to consume dependencies in the start up class?

I've configured my Application and Added a context in the services

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework().AddDbContext<ApplicationContext>(options => 
                                         options.UseSqlServer(connection));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "https://localhost:4430",
        RequireHttpsMetadata = false,

        ApiName = "api",
        JwtBearerEvents = new SyncUserBearerEvent()
        {
            OnTokenValidated = async tokenValidationContext =>
            {

                    var claimsIdentity = tokenValidationContext.Ticket.Principal.Identity as ClaimsIdentity;
                    if (claimsIdentity != null)
                    {
                        // Get the user's ID
                        string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "sub").Value;

                    }

                    //I need to spawn a context here

                }
            }
        }
    });
}

I need to consume this context in the configure method which is called next. I read a few creating a new DbContext, is not proper and it should be consumed from our services.

What's the proper way to Consume a new Db context in the startup method?

Upvotes: 1

Views: 112

Answers (1)

Pankaj Kapare
Pankaj Kapare

Reputation: 7812

Dependencies registered in ConfigureServices method are ready to use once ConfigureServices method call is complete. Since Configure method is fired post ConfigureServices, registered dependencies can be used in Configure method using parameter injection rather newing them up inside method. If you only need a singleton, you can inject services in Configure method as shown below.

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env, 
                      ILoggerFactory loggerFactory,
                      IDependentService service)
{
      //You can use dbContext here.
}

You can also spawn your context from your app services like so:

var dependentService = app.ApplicationServices.GetRequiredService<IDependentService>())

If you need a an dbContext, you will need to access the service provide though the HttpContext. In you're instance you can access it through the TokenValidatedContext that is passed in like so:

var serviceProvider = tokenValidationContext.HttpContext.RequestServices;
using (var context = serviceProvider.GetRequiredService<AstootContext>())
{
}

Upvotes: 2

Related Questions