How to organize your dependencies in .NET
In the world of .NET development, itβs a common practice to establish registrations for dependencies, ranging from basic services to third-party components obtained through NuGet packages.
1/ Inline Dependency Registration
Consider a straightforward example of dependency registration. Below is an illustration of how dependencies would be registered in a Program.cs file.
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<AddSecurityHeader>();
builder.Services.AddScoped<HttpClient>();
builder.Services.AddScoped<IValidator<CreateUserCommand>, CreateUserCommandValidator>();
2/ Extension Method Dependency Registration
The previous approach is suitable but becomes less efficient as the number of dependencies increases.
A more effective strategy involves relocating these dependencies into an extension method and then invoking that extension method within the Program file.
public static IServiceCollection AddApplication Dependencies( this IServiceCollection services)
{
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRoleService, RoleService>();
services.AddScoped<AddSecurityHeader>();
services.AddScoped<HttpClient>();
services.AddScoped<IValidator<CreateUserCommad>, CreateUserCommadValidator>();
return services;
}
Add in Program
builder.Services.AddApplicationDependencies();
3/ Modularized Dependency Registration
I prefer to create distinct extension methods for each concern.
Then, I consolidate the invocation of these methods into a single method, and only this method is called in the Program file.
This ensures a more organized and modular approach to dependency registration.
public static IServiceCollection AddApiDependencies(this IServiceCollection services)
{
services.AddServices();
services.AddDelegateHandlers();
services.AddValidators();
return services;
}
public static IServiceCollection AddServices(this IServiceCollection services)
{
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRoleService, RoleService>();
return services;
}
public static IServiceCollection AddDelegateHandlers(this IServiceCollection services)
{
services.AddScoped<AddSecurityHeader>();
return services;
}
public static IServiceCollection AddValidators(this IServiceCollection services)
{
services.AddScoped<IValidator<CreateUserCommand>, CreateUserCommandValidator>();
return services;
}
Add in Program file
builder.Services.AddApiDependencies();
This way dependencies becomes :
-
More clean
-
Easy to manage
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place