Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 542
user2818430 Avatar asked Oct 29 '22 16:10

user2818430


1 Answers

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
}
like image 51
adem caglin Avatar answered Nov 11 '22 14:11

adem caglin