Apply when working with C#/.NET backend code including controllers, services, and dependency injection
// Program.cs or Startup.cs
var builder = WebApplication.CreateBuilder(args);
// Transient: New instance every time
builder.Services.AddTransient<IEmailService, EmailService>();
// Scoped: One instance per HTTP request
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IOrderService, OrderService>();
// Singleton: One instance for application lifetime
builder.Services.AddSingleton<ICacheService, MemoryCacheService>();
// With factory
builder.Services.AddScoped<IDbContext>(provider =>
{
var config = provider.GetRequiredService<IConfiguration>();
return new DbContext(config.GetConnectionString("Default"));
});
public class OrderService : IOrderService
{
private readonly IOrderRepository _orderRepository;
private readonly IProductService _productService;
private readonly IEmailService _emailService;
private readonly ILogger<OrderService> _logger;
public OrderService(
IOrderRepository orderRepository,
IProductService productService,
IEmailService emailService,
ILogger<OrderService> logger)
{
_orderRepository = orderRepository;
_productService = productService;
_emailService = emailService;
_logger = logger;
}
public async Task<Order> CreateOrderAsync(CreateOrderRequest request, CancellationToken ct)
{
_logger.LogInformation("Creating order for customer {CustomerId}", request.CustomerId);
// Implementation
}
}
// Focused interfaces
public interface IProductReader
{
Task<Product?> GetByIdAsync(Guid id, CancellationToken ct);
Task<IReadOnlyList<Product>> GetAllAsync(CancellationToken ct);
Task<IReadOnlyList<Product>> SearchAsync(string query, CancellationToken ct);
}
public interface IProductWriter
{...