Castle windsor - service override for downstream dependencies

Viewed 27

Assume I have interfaces A, B, C, D, and E, and F.

I am trying to set up a windsor container in such a way that my application has two instances of D, lets call them D1 and D2. A is bound with singleton lifetime.

I am looking to inject D according to the following logic: If the dependency chain has an (the) instance of "A" anywhere further upstream, then inject instance D2. If that is not the case, inject D1.

  A               F
 / \              |
B   C             D1
   / \
  D2   E
      |
      D2
     

What's the simplest and best way to achieve this?

At the moment, I'm doing something like

Component.For<A>().ImplementedBy<SomeAImpl>().DependsOn((_, d) d['SomeKey'] = 'SomeTriggerValue')

For each of the potential child-components of A (or potential child-of-child components etc.), I'm binding those with a custom scope that checks AdditionalArgs for this key, and finally, I'm binding different instances of D (D1 and D2) according to these scopes.

That seems super messy, so I wonder whether there's any better ways to do this?

1 Answers

Generally, my perspective would be that while semantically D1 and D2 may be instances of the same interface (in terms of the contracts they represent) they are not substitutable in a dependency injection sense.

Therefore I would either:

a) create derived interfaces of D that described the dependency injection contextual differences and make F dependent on the first and C&E dependent on the second, or

b) (typically if the dependency injection is occurring within the same assembly) express the dependency requirement using the CLASS type, rather than the INTERFACE type.

Related