Reputation: 1986
I have the following object graph that I would like to resolve using an IoC container:
Here, B(#1)
and B(#2)
are of the same type but different instances, same with C(#1)
and C(#2)
, and D(#1)
and D(#2)
. I would like to resolve A
.
The problem is that there are two instances of D
that four other objects have as a dependency. Depending on how I set the lifecycle of D
, I will either get one instance that all of them share, or I will get four different instances.
I am currencly using StructureMap, but the solution could use another IoC container if some feature is needed that StructureMap doesn't have.
The actual use case (as per request in the comments):
The object graph is found inside a WPF application where I have separated the responsibilities of the typical MVVM ViewModel into a ViewModel and a Controller. In the image above, D
is a ViewModel that only contains the state and C
is a Controller that executes commands. B
is the DataContext that the XAML binds to.
B
, C
and D
are part of a user control. A
is a DataContext that contains two instances of the user control.
Upvotes: 2
Views: 182
Reputation: 172646
I think the trick is to register D
as per-request (which is StructureMap's default lifestyle) and make a registration for A that explicitly resolves the two B's:
For<A>().Use(s =>
{
var b1 = s.GetInstance<B>();
var b2 = s.GetInstance<B>();
return new A(b1, b2);
});
This ensures that for each resolved graph of B
, there will be exactly one D
, and since your object graph probably consists of much more than just A
, B
, C
, and D
, this ensures that you only have to fall back to using manual wiring for A
and this keeps your dependency graph the most maintainable.
Upvotes: 1
Reputation: 11964
You can use factory method:
For<B>().Use(s =>
{
var d = s.GetInstance<D>();
var c = new C(d);
return new B(c,d);
});
Upvotes: 1