简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM