Resolve and Initialize the Instances within ConfigServices of ASP.NET Core
In this article, we will see how to resolve instances within ConfigServices in ASP.NET Core. Then we shall see how to initialize the instances within the ConfiguerServices method.
This could be useful on many occasions that you would like to resolve the instances and then use the same configured instances as DI across API layers using constructor injection.
Today in this article we will see a simple and easy approach of resolving the instances right within the ConfigServices method.
Today in this article, we will cover below aspects,
Such instances which are resolved in ConfigServices() can be injected API pipeline as required. The good thing is that you can use these instances anywhere in any class, as long as you use them through DI. Such instances also get destroyed by the framework depending on the lifetime of instances declared in ConfigServices() method.
Getting started
Let’s create any ASP.NET Core application,
Resolve Instances within ConfigServices
The easiest way to resolve the Instances within ConfigServices is to use ServiceProvider which helps us creating a provider containing the services from IServiceCollection.
Example:
Example – Please see example 2 explained below.
Note: Instead of using ServiceProvider please see if you can use options pattern’s built-in support for DI
Resolve Instances within the Configure method
If you ever need to resolve the instances within the Configure method in ASP.NET Core 3.1 then please use IApplicationBuilder directly to get access to the required services in the API pipeline.
Resolving scoped instance
Resolving Transient or Singleton instances are straight forward however if you have scoped instances then kindly create a scope object first using the CreateScope method.
Use the scope object to query service providers to get the service instance using GetService() extension methods.
Resolving Transient or Singleton instances
Resolving Transient or Singleton instances is straightforward. You can call GetService() method directly using the App object as below,
var service= app.ApplicationServices.GetService<IUniqueIdService>();
string guid = service.GetDetails();
How to Initialize the Instances within ConfigServices
Let’s see how to resolve and at the same time Initialize the instances within ConfigServices of ASP.NET Core.
We shall be using the below pattern to resolve the dependency and initialize the instances.
services.AddSingleton<IYourInterface, YourClass>(op => {
//Resolve and initialize the logic here
return obj;
});
Let’s see a real example using the above pattern.
Example 1:
You must have heard of the IOption pattern where it lets you inject Key Value Pair values as DI. We will perform similar DI but without using IOption pattern.
Performing Key-Value DI without using IOption
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<ICustomerConfig, CustomerConfig>(op => {
CustomerConfig obj = new CustomerConfig();
obj.Agency = new Agency();
obj.CustomerKeyurl = Configuration.GetValue<string>("Customer:CustomerKeyurl");
obj.CustomerdetailsUrl = Configuration.GetValue<string>("Customer:CustomerKeyurl");
obj.Agency.AccountKey = Configuration.GetValue<int>("Customer:Agency:AccountKey");
obj.Agency.AgencyID = Configuration.GetValue<string>("Customer:Agency:AgencyID");
return obj;
});
}
- Here we are defining and initializing the Instance at the StartUp
- The Instance will be initialized with data like bootstrapping on the startup.
- Can be used for feeding the data at startup.
- The lifetime of the instance will be controlled based on the lifetime instance
Once executed interface ICustomerConfig gets resolved and initialized using Constructor injection in Controller or any other class where you need the data as below,
Example 2:
In the below example we are registering the instances by resolving the dependency from the other service instance and their method data and then initializing it.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IUniqueIdService, UniqueIdService>();
services.AddScoped<ICustomerConfig, CustomerConfig>(op =>
{
CustomerConfig obj = new CustomerConfig();
var myCustomService = op.GetService<IUniqueIdService>();
obj.Guid = myCustomService.GetDetails();
return obj;
});
}
With the above we are registering and initializing the ICustomerConfig using the third party service (or your other service instance)) i.e IUniqueIdService using unique GUID code.
References
That’s all! Can we make the above code better?
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Summary
Today in this article we looked at a few approaches of resolving the service instances within ConfigureService and Configure methods in Startup.cs file. We also learned to initialize instances in a startup so that those can be used using DI in application as needed.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.