Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET Core, how do I use a service that is setup in ConfigureServices() in Configure()?

I have a service I wrote that helps with configuration. The service is set up in the Startup class's ConfigureServices method as:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddScoped<IMyService, MyService>();

    ...
}

I need to then get an instance of IMyService in the Startup class's Configure method. How do I do that?

like image 868
David Derman Avatar asked Mar 15 '17 16:03

David Derman


1 Answers

Since you've already added your service with AddScoped, all you need to do is add another parameter to the Configure method with the correct type and the dependency injection system will take care of it for you:

public void Configure(IApplicationBuilder app, 
    IHostingEnvironment env, 
    ILoggerFactory loggerFactory, 
    IMyService myService)
{
    //Snip
}
like image 76
DavidG Avatar answered Oct 04 '22 15:10

DavidG