标签: decorator-pattern

依赖关系注入以提供通用服务接口的最特定实现的机制

我觉得我像标题一样玩了流行语宾果游戏。这是我要问的一个简洁示例。假设我对某些实体有一些继承层次结构。

class BaseEntity { ... }
class ChildAEntity : BaseEntity { ... }
class GrandChildAEntity : ChildAEntity { ... }
class ChildBEntity : BaseEntity { ... }
Run Code Online (Sandbox Code Playgroud)

现在让我们说说我为服务提供了一个通用接口,该接口具有使用基类的方法:

interface IEntityService<T> where T : BaseEntity { void DoSomething(BaseEntity entity)... }
Run Code Online (Sandbox Code Playgroud)

我有一些具体的实现:

class BaseEntityService : IEntityService<BaseEntity> { ... }
class GrandChildAEntityService : IEntityService<GrandChildAEntity> { ... }
class ChildBEntityService : IEntityService<ChildBEntity> { ... }
Run Code Online (Sandbox Code Playgroud)

假设我已经将所有这些都注册到了容器中。所以,现在我的问题是,如果我迭代通过ListBaseEntity?我如何获得注册的服务与最接近的匹配?

var entities = List<BaseEntity>();
// ...
foreach(var entity in entities)
{
    // Get the …
Run Code Online (Sandbox Code Playgroud)

c# generics dependency-injection strategy-pattern decorator-pattern

6
推荐指数
1
解决办法
353
查看次数