5

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.

2
  • Just crossed my mind ... maybe if I used a custom service middleware and run my logic in there? Nov 21, 2016 at 7:33
  • What kind of logic you need to execute? is it per request or just once when the application starts? Nov 21, 2016 at 9:46

1 Answer 1

2

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.