Giải thích về Dependency Injection (DI) trong ASP.NET Core
Giải thích về Dependency Injection (DI) trong ASP.NET Core
Dependency Injection (DI) trong ASP.NET Core là tính năng tích hợp sẵn (Microsoft.Extensions.DependencyInjection): đăng ký dịch vụ vào container và nhận chúng qua constructor.
// Đăng ký
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddTransient<IMailer, SmtpMailer>();
builder.Services.AddDbContext<AppDbContext>(...); // Scoped
builder.Services.AddHttpClient<IGithubClient, GithubClient>();
// Sử dụng
public class OrdersController(IOrderRepository repo, ILogger<OrdersController> log) : ControllerBase { }
// Minimal API: tham số tự được tiêm
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.