OneDeveloper
✅ Generic DI in minimal APIs
public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddMediatR(config => config.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));
//builder.Services.AddMediatR(config => config.RegisterServicesFromAssemblyContaining<Program>());
services.AddAutoMapper(typeof(DependencyInjection));
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
return services;
}
34 replies
✅ Generic DI in minimal APIs
using CQRS.Api;
using CQRS.Api.Controllers;
using CQRS.Application;
using CQRS.Contracts;
using CQRS.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
var Services = builder.Services;
#region Configure Services
Services.AddControllers();
Services.AddScoped<RequestPayload>();
Services.AddApplication()
.AddInfrastructure(builder.Configuration);
#endregion
var app = builder.Build();
#region Configure Global Exception Handling
app.UseExceptionHandler("/error");
//app.UseExceptionHandler(ex =>
//{
// ex.Run(async context =>
// {
// context.Response.StatusCode = StatusCodes.Status500InternalServerError;
// context.Response.ContentType = "text/plain";
// Exception? exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
// var requestPayload = context.RequestServices.GetRequiredService<RequestPayload>();
// var respose = new ApiResponse(requestPayload: requestPayload,
// statusCode: StatusCodes.Status500InternalServerError,
// message: "An unexpected error Occurred",
// response: exception.Message);
// await context.Response.WriteAsJsonAsync(respose);
// });
//});
#endregion
#region Configure Pipeline & Middleware
app.UseMiddleware<Middleware>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
#endregion
#region Configure COntrollers & Minimal APIs
app.MapControllers();
//Minimal API for Register/Login
app.MapAuthEndpoints();
//using (var scope = app.Services.CreateScope())
//{
// var service = scope.ServiceProvider.GetRequiredService<AuthController>();
// service.MapAuthEndpoints(app);
//}
#endregion
app.Run();
34 replies
✅ Generic DI in minimal APIs
public static void MapAuthEndpoints(this WebApplication app)
{
using var scope = app.Services.CreateScope();
IMediator mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
RequestPayload requestPayload = scope.ServiceProvider.GetRequiredService<RequestPayload>();
var auth = app.MapGroup("auth");
auth.MapPost("login", async (HttpContext context, LoginRequest loginRequest) =>
{
var response = await mediator.Send(new LoginCommand(loginRequest));
return new ApiResponse(requestPayload: requestPayload, statusCode: context.Response.StatusCode, response: response);
});
auth.MapGet("role/{id:Guid}",GetRoleAsync);
}
34 replies