services.AddScoped<IServiceA,ServiceA>(); public WeatherForecastController(IServiceA service) { }但是,有时可能需要在同一ASP.NET Core 应用程序中使用同一接口的不同实现。
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>>()));
services.AddControllers().AddControllersAsServices();