ASP.NET ConfigureServices
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨ASP.NET 8中的ConfigureServices方法。此方法对于配置应用程序服务和依赖项至关重要。
ASP.NET是一个跨平台的、高性能的框架,用于构建现代Web应用程序。ConfigureServices是注册服务以进行依赖项注入的地方。
基本定义
ASP.NET中的ConfigureServices方法是应用程序启动过程的一部分。它由运行时调用,以将服务添加到DI容器中。
在ConfigureServices中注册的服务将在您的整个应用程序中可用。这包括框架服务和您自己的自定义服务。
ConfigureServices接收一个IServiceCollection参数,该参数提供了服务注册方法。该方法在Configure之前被调用。
ASP.NET ConfigureServices示例
以下示例演示了一个基本的Web API及其服务配置。
Program.cs
var builder = WebApplication.CreateBuilder(args);
// ConfigureServices equivalent in .NET 6+ minimal APIs
builder.Services.AddControllers();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers();
app.Run();
这展示了现代.NET 8的服务配置方法。builder.Services属性取代了传统的ConfigureServices。
我们注册了控制器、一个存储库接口、Entity Framework DbContext和Swagger文档。每种服务都有一个特定的生命周期(此处为Scoped)。
Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Repositories/IProductRepository.cs
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product GetById(int id);
void Add(Product product);
}
Repositories/ProductRepository.cs
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context)
{
_context = context;
}
public IEnumerable<Product> GetAll() => _context.Products.ToList();
public Product GetById(int id) => _context.Products.Find(id);
public void Add(Product product) => _context.Products.Add(product);
}
存储库模式抽象了数据访问。接口和实现都在ConfigureServices中注册。Entity Framework处理数据库操作。
Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _repository;
public ProductsController(IProductRepository repository)
{
_repository = repository;
}
[HttpGet]
public ActionResult<IEnumerable<Product>> Get()
{
return Ok(_repository.GetAll());
}
[HttpGet("{id}")]
public ActionResult<Product> Get(int id)
{
var product = _repository.GetById(id);
if (product == null) return NotFound();
return Ok(product);
}
}
控制器演示了依赖项注入的实际应用。存储库通过构造函数注入,这得益于ConfigureServices的注册。
此示例展示了一个完整的流程:服务注册、接口实现以及通过DI进行消费。该模式促进了松耦合。
来源
在本文中,我们探讨了ASP.NET 8中的ConfigureServices。这一基本概念通过依赖项注入实现了清晰的架构。