• 如何在 ASP.NET Core 中为同一接口配置不同的实现
  • 发布于 2个月前
  • 328 热度
    0 评论
  • 心已凉
  • 8 粉丝 34 篇博客
  •   
前言
通常,我们使用依赖注入时,一个接口仅对应一种实现,使用时可以直接得到实现类的实例,类似这样:
services.AddScoped<IServiceA,ServiceA>();
public WeatherForecastController(IServiceA service) { }
但是,有时可能需要在同一ASP.NET Core 应用程序中使用同一接口的不同实现。

下面是不同需求下对应的解决方案。

为不同的类型使用不同实现
例如仓储接口IRepository<>,默认使用EF core访问关系型数据库,而对于特定实体(例如订单Order)使用MONGODB存储。

可以首先注册默认实现,再针对特定实体注册指定实现:
services.AddScoped(typeof(IRepository<>), typeof(EFCoreRepository<>));
services.AddScoped(typeof(IRepository<Order>), typeof(MongoRepository<Order>));


在不同的Controller中使用不同实现

例如订单仓储接口IRepository,默认使用MONGODB存储,而在报表服务ReportController中访问ES。

可以针对构造函数注册指定参数:
services.AddScoped<ESRepository<Order>>();
services.AddScoped(x => new ReportController(x.GetRequiredService<ESRepository<Order>>()));

注意:以上方式需要使用命令将Controller添加为服务才能使用:
services.AddControllers().AddControllersAsServices();


用户评论