我使用的是默认的ASP.NET核心DI容器
我的层次结构:
interface IRepo<T> where T : Entity; - (CRUD)
interface ICarRepo : IRepo<Car>; - (CRUD + more specific actions)
class CarRepo : ICarRepo; - implStartup.cs
service.addtransient<ICarRepo, CarRepo>();所以有时候我可以直接向IoC-container请求ICarRepo并得到它。
但是,如果我想通过请求IRepo<Car>来获得CarRepo,我应该如何注册我的依赖项呢?
我知道该怎么做:
service.addtransient<ICarRepo, CarRepo>();
service.addtransient<IRepo<Car>, CarRepo>();但这看起来并不是最好的方式
发布于 2020-11-18 21:58:19
正如您所描述的
service.addtransient<ICarRepo, CarRepo>();
service.addtransient<IRepo<Car>, CarRepo>();就是这样做的一种方式。因为它是暂时的,所以每次都会生成一个新的实例并不重要。虽然你也可以在这里使用“转发”风格。
当试图确保为singleton或scoped服务返回相同的实例时,就会变得更加棘手。在这种情况下,您需要转发工厂方法。
services.AddSingleton<Foo>();
services.AddSingleton<IFoo>(x => x.GetRequiredService<Foo>());更详细的解释可以在this blog article上找到。
https://stackoverflow.com/questions/64894234
复制相似问题