7.7 — 5. Program.cs và WebApplicationBuilder
Mục tiêu bài học
- Nắm được ý chính của bài và mối liên hệ với module.
- Áp dụng được kiến thức vào bối cảnh CRM/.NET backend.
- Sẵn sàng chuyển sang bài kế tiếp với nền tảng chắc chắn.
Nội dung bài học
7.7.1 — Cấu trúc setup trong ASP.NET Core
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Đăng ký service theo từng layer — tách thành extension methods
builder.Services
.AddInfrastructure(builder.Configuration)
.AddApplication()
.AddPresentation();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.UseSwagger().UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();
7.7.2 — Extension Methods theo layer
// Infrastructure/DependencyInjection.cs
public static class InfrastructureDependencyInjection
{
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<CrmDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("CrmDb")));
services.AddScoped<ICustomerRepository, EfCustomerRepository>();
services.AddScoped<ILeadRepository, EfLeadRepository>();
services.AddScoped<IUnitOfWork, EfUnitOfWork>();
services.Configure<EmailSettings>(
configuration.GetSection(EmailSettings.SectionName));
services.AddSingleton<IEmailService, SmtpEmailService>();
return services;
}
}
// Application/DependencyInjection.cs
public static class ApplicationDependencyInjection
{
public static IServiceCollection AddApplication(
this IServiceCollection services)
{
services.AddScoped<ICustomerService, CustomerService>();
services.AddScoped<ILeadService, LeadService>();
services.AddTransient<ILeadScorer, RuleBasedLeadScorer>();
// Đăng ký tất cả handler trong assembly
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(ApplicationDependencyInjection).Assembly));
return services;
}
}
Bài tập áp dụng
- Tóm tắt bài học bằng ngôn ngữ của bạn.
- Liên hệ nội dung với một tình huống thực tế trong dự án.
- Đề xuất một cải tiến cụ thể sau khi học bài này.
Tự kiểm tra
- Bạn có thể giải thích lại nội dung chính trong 2 phút không?
- Bạn có ví dụ áp dụng thực tế chưa?
- Bạn biết bước tiếp theo cần học/triển khai là gì không?
Kết luận
Hoàn thành bài này giúp bạn có góc nhìn đầy đủ hơn trước khi đi tiếp trong module.
Điều hướng
- Bài trước: 7.6 — 4. Registering Services
- Bài tiếp theo: 7.8 — 6. Options Pattern
- Về module: Trang mục lục