How to Pre-Configure Services Before Registering with ASP.NET Core's Built-in Service Container
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 😊