简体   繁体   中英

Design for interface that can be “implemented N times”

Currently I'm using a generic interface to declare IoC dependencies like this:

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. 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 . 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM