RSS Amplifier

sahansera.dev RSS Feed · Dec 1, 2019

How to Pre-Configure Services Before Registering with ASP.NET Core's Built-in Service Container

0
Sign in to vote or save

Sahan Serasinghe · Sahan Serasinghe

In ASP.NET, if you are using the default DI service container, registering services is done in the ConfigureServices(IServiceCollection) method in your Startup.cs class.

In some special situations, you may want to take control of the instantiation of some service. The idea here is to inject any other dependencies that a service would require before registering with your DI container; ASP.NET Core’s default service container in our example.

Here is an example:

services.AddScoped<IComputerVisionClient, ComputerVisionClient>((serviceProvider) =>
{
    ConfigService configService = serviceProvider.GetService<ConfigService>();
    return new ComputerVisionClient(
        new ApiKeyServiceClientCredentials(configService.SubscriptionKey),
        new System.Net.Http.DelegatingHandler[] { })
    {
        Endpoint = configService.Endpoint
    };
});

The above code sits in your ConfigureServices(IServiceCollection services) method when registering your service.

In simple terms, it instantiates ComputerVisionClient by using another component. We can obtain a reference to another service ConfigService which is used to keep our configurations in.

Now you should be able to inject that service in your controllers/services 😊

The factory overload used above is one of several ways the built-in container can be told how to build something. Having Fun with Microsoft IoC Container for .NET Core builds the same container up from an empty console app, which is the clearest way to see why this overload exists at all.

Read the original on sahansera.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.