考虑以下内容:
public class DependencyA {}
public class DependencyB {}
public class DependencyC {}
public class DependencyD {}
public class Service1
{
public Service1(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}
public class Service2
{
public Service2(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}
public class Service3
{
public Service3(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}
我发现我的许多服务都依赖于多个通用组件,并且正在考虑实现如下所示的全部解决方案(全部通过 Windsor 连接)以节省服务构造函数中的代码重复。
public class DependencyContainer
{
public DependencyA A { get; set; }
public DependencyB B { get; set; }
public DependencyC C { get; set; }
public DependencyD D { get; set; }
}
public class Service1
{
public Service1 (DependencyContainer container) { ... }
}
或者,我可以创建一个 ServiceBase 类。
public class ServiceBase
{
public DependancyA A { get; set; }
public DependancyB B { get; set; }
public DependancyC C { get; set; }
public DependancyD D { get; set; }
}
public class Service1 : ServiceBase {}
真正的问题是,这是否突出了服务中更广泛的设计问题?
也许我把 DI 走得太远了,但这些都是真正的依赖。
如果是这样,我该如何解决这个问题?如果不是,建议的解决方案是实现这一目标的有效方法吗?