Reputation: 3099
I have a scenario in which I need to be able to get two different implementations of an interface IObjectContext
from StructureMap. I know that using a named instance is the answer but I'm having trouble with the DSL for this because the class to "use" is also the same in each case, but with a different constructor parameter.
So, the way to create these objects outside of StructureMap are as follows:
IObjectContext context1 = new ObjectContextAdapter(new Model1Entities());
IObjectContext context2 = new ObjectContextAdapter(new Model2Entities());
How can I express this configuration in StructureMap Registry DSL? I know that I need to use named instances but I can't get my head around the rest of the syntax.
Thanks!!!
Upvotes: 0
Views: 633
Reputation: 961
We came across a similar problem recently while attempting to register multiple named instances of the same concrete type (in our case this was within a custom Scanner) - Structuremap doesn't allow you to do this directly.
In the end we had to use the ConstructedBy method, passing in an expression that explicitly instanciated the concrete type.
Worth checking here StructureMap - Configuring Instances as a starting point.
Edit: I think this is the sort of thing you probably want in your registry (thanks to PHeiberg for the Add() suggestion):
For<IObjectContext>().Add(() => new ObjectContextAdapter(new Model1Entities())).Named("objectContext1");
For<IObjectContext>().Add(() => new ObjectContextAdapter(new Model2Entities())).Named("objectContext2");
Upvotes: 1
Reputation: 3768
It might not be a good solution in your case but you could create 2 separate adapter classes one for each instance of model entities. This makes the fact clear that the objects are not the same. You could easily derive both from the same baseclass to make the implementation very easy.
Upvotes: 0