ASP.NET Core 1.0 access service in ConfigureServices method (Startup.cs)

asp.net-core-1.0 c# entity-framework-core

Question

A basic ConfigureServices method looks like this:

public void ConfigureServices(IServiceCollection services)
{

services.AddDbContext<ApplicationDbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

services.AddMvc();

services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();

  //custom logic here
}

Right before the method ends I want to run some custom logic. However I need to access the ApplicationDbContext and get some configuration from there. Another thing is I want to use the AuthMessageSenver service to send an email.

My question: how can I access a service I declared within the same method. Or how can I use my ApplicationdDbContext to get the data from database.

1
4
11/21/2016 7:31:08 AM

Popular Answer

You can use BuildServiceProvider method to resolve a service:

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddTransient<IEmailSender, AuthMessageSender>();
    //...

    var provider = services.BuildServiceProvider();
    var emailSender= provider.GetService<IEmailSender>();
    // use emailSender
}
2
11/21/2016 9:28:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow