[英]Design for interface that can be “implemented N times”
Currently I'm using a generic interface to declare IoC dependencies like this: 目前,我正在使用通用接口来声明IoC依赖关系,如下所示:
public interface IComposition<T>
{
T Dependency { get; set; }
}
But happens that my implementations could have more than one dependency at same time. 但是碰巧我的实现可能同时具有多个依赖关系。
I know it's ridiculous, but just to you guys understand what I need... let's say I implement the interface multiple times to solve my problem: 我知道这很荒谬,但是只是为了让你们了解我需要的东西。假设我多次实现了该接口来解决我的问题:
public class MyClass : IComposition<TypeA>, IComposition<TypeB>
{
...
}
I believe that using IComposition<T1, T2, ...>
or one ITypeXDependent
for each type aren't good options. 我相信对每种类型使用IComposition<T1, T2, ...>
或一个ITypeXDependent
都不是很好的选择。 My core needs to resolve dependencies at runtime using reflection. 我的核心需要在运行时使用反射来解决依赖关系。 So, thats why I'm not passing dependencies through the constructor. 因此,这就是为什么我没有通过构造函数传递依赖项的原因。
Does anyone know some trick that can help me out? 有谁知道一些可以帮助我的把戏?
I would use constructor parameters instead of your current scheme to set up dependencies: 我将使用构造函数参数而不是当前方案来设置依赖关系:
public class MyClass
{
public void MyClass(TypeA a, TypeB b)
{
....
}
}
Aside regular interfaces, generic interfaces can be "implemented N times" since each generic type parameter used create another interface type . 除了常规接口之外,通用接口可以“实现N次”,因为使用的每个通用类型参数都会创建另一个接口类型 。 The only thing to care about is to implement the interface explicitly: 唯一需要注意的是显式实现接口:
public interface IComposition<T>
{
T Dependency { get; set; }
}
public class MyClass: IComposition<TypeA>, IComposition<TypeB>
{
IComposition<TypeA>.TypeA Dependency { get; set; }
IComposition<TypeB>.TypeB Dependency { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.