In ASP.NET Core MVC, the dependency injection (DI) mechanism is used to manage the creation and life cycle of application dependencies. The ConfigureServices
method is typically used to register dependencies, but it initially only creates a IServiceCollection
collection that acts as a blueprint for the DI container.
To manually resolve the service instance, we need to obtain a IServiceProvider
which contains the fully composed container. There are several ways to achieve this:
Injecting services into the Startup
class's constructor allows direct access to built-in services in ConfigureServices
methods, e.g. IConfiguration
:
<code class="language-csharp">public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // 在此处使用 Configuration } }</code>
In the Configure
method, IApplicationBuilder
provides direct access to IServiceProvider
:
<code class="language-csharp">public void Configure(IApplicationBuilder app) { var serviceProvider = app.ApplicationServices; var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>(); }</code>
To resolve dependencies directly in ConfigureServices
you need to use an intermediate service provider:
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IFooService, FooService>(); var sp = services.BuildServiceProvider(); var fooService = sp.GetService<IFooService>(); }</code>
Manual resolution of dependencies (service locators) is generally not recommended as it may reduce maintainability and testability. Prefer injecting dependencies whenever possible.
The above is the detailed content of How Can I Resolve ASP.NET Core DI Instances within ConfigureServices?. For more information, please follow other related articles on the PHP Chinese website!