Dynamic Service Registration in ASP.NET Core Dependency Injection Container






4.75/5 (5 votes)
How to dynamically register all services as a dependency to an ASP.NET Core Dependency Injection container
Introduction
In ASP.NET Core, whenever we inject a service as a dependency, we must register this service to ASP.NET Core Dependency Injection container. But registering services one by one is not only tedious and time-consuming, but also it is error-prone. So here, we will discuss how we can register all the services at once dynamically.
Let's Get Started!
To register all the services dynamically, we will use AspNetCore.ServiceRegistration.Dynamic
library. This is a small but extremely useful library that enables you to register all your services into ASP.NET Core Dependency Injection container at once without exposing the service implementation.
Now first install the latest version of AspNetCore.ServiceRegistration.Dynamic
nuget package into your project as follows:
Install-Package AspNetCore.ServiceRegistration.Dynamic
Using Marker Interface:
Now let your services inherit any of the ITransientService
, IScoperService
and ISingletonService
marker interfaces as follows:
// Inherit `IScopedService` interface if you want to register `IEmployeeService`
// as scoped service.
public class IEmployeeService : IScopedService
{
Task CreateEmployeeAsync(Employee employee);
}
internal class EmployeeService : IEmployeeService
{
public async Task CreateEmployeeAsync(Employee employee)
{
// Implementation here
};
}
Using Attribute:
Now mark your services with any of the ScopedServiceAttribute
, TransientServiceAttribute
and SingletonServiceAttribute
attributes as follows:
// Mark with ScopedServiceAttribute if you want to register `IEmployeeService` as scoped
// service.
[ScopedService]
public class IEmployeeService
{
Task CreateEmployeeAsync(Employee employee);
}
internal class EmployeeService : IEmployeeService
{
public async Task CreateEmployeeAsync(Employee employee)
{
// Implementation here
};
}
Now in your ConfigureServices
method of the Startup
class:
public static void ConfigureServices(IServiceCollection services)
{
services.AddServicesOfType<IScopedService>();
services.AddServicesWithAttributeOfType<ScopedServiceAttribute>();
}
AddServicesOfType<T>();
and AddServicesWithAttributeOfType<T>();
are available in AspNetCore.ServiceRegistration.Dynamic.Extensions
namespace.
Conclusion
That's it! The job is done! It is as simple as above to dynamically register all your services into ASP.NET Core Dependency Injection container at once. If you have any issues, you can submit it to the Github Repository of this library. You will be helped as soon as possible.
Thank you for reading!
History
- 9th April, 2020: Initial version.
- 16th April, 2020 : Updated for attribute-based registration.