Home >Backend Development >C++ >How Can I Resolve ASP.NET Core DI Instances within ConfigureServices?

How Can I Resolve ASP.NET Core DI Instances within ConfigureServices?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 08:37:07223browse

How Can I Resolve ASP.NET Core DI Instances within ConfigureServices?

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:

Dependency injection via constructor

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>

Manually resolve dependencies in Configure method

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>

Resolving dependencies in ConfigureServices

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>

Notes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn