Search code examples
.netdryioc

DryIoc: Register with a different Dependency of a Dependency


How can I override a Dependency of a Dependency in a Register-Statement?

For Example:

class A {
  public A(IB b) {}
}

class MyService {
  public MyService(A a) {}
}

cnt.Register<MyService>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB")); // ignored by dryioc, because it's a Dependency of Dependency A
cnt.Register<IB, OtherB>(serviceKey: "otherIB");

I think it's a simple question, if other explanation needed, I will edit the question.


Solution

  • Dependency of dependency is a nested thing which is not visible to the first dependency owner. Otherwise it will break an isolation - why should I know about my dependencies implementation details (their dependencies)?

    To fix the code you need to add registration for A:

    cnt.Register<MyService>();
    cnt.Register<A>(made: Parameters.Of.Type<IB>(serviceKey: "otherIB"));
    cnt.Register<IB, OtherB>(serviceKey: "otherIB");
    

    Update:

    From the other hand, if you want a context based dependency, you can register it with condition:

    cnt.Register<IB, OtherB>(setup: Setup.With(condition:
        req => req.Parent.Enumerate().Any(p => p.ServiceType == typeof(MyService)));
    
    cnt.Register<IB, DefaultB>(setup: Setup.With(condition:
        req => req.Parent.Enumerate().All(p => p.ServiceType != typeof(MyService)));