A clean way to implement dependency injection(DI) in startup.cs on .Net Core Web Project with CQRS & MediatR.
Web Project had configured with few of layered class libiary project, swagger installation for the API documentaion and CORS for resource sharing.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
/** Application layer & Infrastructure layer DI reference */
services.AddApplication();
services.AddInfrastructure();
/** Swagger reference */
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CQRS With MediatR APIs", Version = "v1" });
});
/** CORS reference */
services.AddCors(options =>
{
options.AddPolicy(name: "MyAllowSpecificOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.InstallServicesInAssembly(Configuration);
}
- Create a folder(named as: Installers) in the API layer
- Create an interface
public interface IInstaller
{
void InstallServices(IServiceCollection services, IConfiguration configuration);
}
- Create respective DI classes and inherit IInstaller interface
- DI
public class DIInstaller : IInstaller { public void InstallServices(IServiceCollection services, IConfiguration configuration) { services.AddControllers(); services.AddApplication(); services.AddInfrastructure(); } }
- Swagger
public class SwaggerInstaller : IInstaller { public void InstallServices(IServiceCollection services, IConfiguration configuration) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "CQRS With MediatR APIs", Version = "v1" }); }); } }
- CORS
public class CorsInstaller : IInstaller { public void InstallServices(IServiceCollection services, IConfiguration configuration) { services.AddCors(options => { options.AddPolicy(name: "MyAllowSpecificOrigins", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); } }
- Create a class that extends Microsoft.Extensions.DependencyInjection
public static class InstallerExtensions { public static void InstallServicesInAssembly(this IServiceCollection services, IConfiguration configuration) { typeof(Startup).Assembly.ExportedTypes .Where(x => typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract) .Select(Activator.CreateInstance).Cast<IInstaller>() .ToList() .ForEach(installer => installer.InstallServices(services, configuration)); } }
- In startup.cs under services section clean the existing code and include below mentioned code
services.InstallServicesInAssembly(Configuration);