Manually resolve the service in the ConfigureServices
method of ASP.NET Core
ASP.NET Core uses the IServiceCollection
interface to build a dependency injection (DI) container. Once built, it is composed into a IServiceProvider
instance that allows you to resolve services. This article guides how to manually parse instances in the ConfigureServices
method.
Inject dependencies
TheConfigureServices
method does not allow service injection, so you can inject services into the constructor of the Startup
class, such as IConfiguration
, IWebHostEnvironment
and ILoggerFactory
.
<code class="language-csharp">public Startup(IConfiguration configuration) => Configuration = configuration; public void ConfigureServices(IServiceCollection services) => services.AddScoped<IFooService>();</code>
Manually resolve dependencies in Configure()
You can manually resolve the service in the IApplicationBuilder
method using the ApplicationServices
attribute of Configure()
:
<code class="language-csharp">public void Configure(IApplicationBuilder app) { var serviceProvider = app.ApplicationServices; var fooService = serviceProvider.GetService<IFooService>(); }</code>
Manually resolve dependencies in ConfigureServices()
To resolve services in ConfigureServices
, use BuildServiceProvider()
to construct an intermediate IServiceProvider
to access services registered up to that point:
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IFooService>(); var sp = services.BuildServiceProvider(); var fooService = sp.GetService<IFooService>(); }</code>
Warning:
Avoid resolving services in ConfigureServices
as it should focus on configuring application services. Consider manually binding the value from IConfiguration
to the instance, or using overloads of AddSingleton
/AddScoped
/AddTransient
to lazily create the instance.
Manually resolving services (service locators) is an anti-pattern and should be used with caution.
The above is the detailed content of How Can I Manually Resolve Services within ASP.NET Core's `ConfigureServices` Method?. For more information, please follow other related articles on the PHP Chinese website!