Forget the neverending argument on the ALT.NET list about whether or not it’s acceptable to inject services into an Entity object (for the record, I say “no way”). What if you want to go the other way around? What if you want to request a service or a view or a command of some kind and have an Entity injected into the service/view/command? You’ve now got (at least) 2 ways to do that in StructureMap.
If you already have the Entity
If you’ve already got the Entity you want, you “pass” the Entity object into ObjectFactory (or an IContainer). Let’s say you have a view named TradeView like this:
If you already have the Trade object in memory, you can grab the IView that displays the Trade by using the Container.With().GetInstance<T>() methods:
The “explicit arguments” to GetInstance<T>() will be propogated all the way through the object graph. Let’s say we have a class named Command that takes in an IView, a Trade, and a Node object in its constructor. The actual object passed to the Command constructor might be a TradeNode class that, surprise, needs a Trade object as well. An elided version of these classes is shown below:
When we request an instance of the Command class using a known Trade object, all of the classes (Command itself, TradeView, and TradeNode) that need a Trade object in their constructor would get the Trade object we specified in …With<Trade>(theTrade)… below:
If you had more than one IView that displayed a Trade object, you could also do this:
and have the known Trade object passed into every instance of TradeView.