Using StructureMap 2.5 to inject your Entity objects into Services

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:


    public class TradeView : IView


        private readonly Trade _trade;


        public TradeView(Trade trade)


            _trade = trade;



        public Trade Trade


            get { return _trade; }



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:


        public void Example()


            IContainer container = new Container();

            Trade theTrade = new Trade();


            var view = container.With<Trade>(theTrade).GetInstance<TradeView>();




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:

    public class Command


        public Command(Trade trade, Node node, IView view)





    public class TradeNode : Node


        public TradeNode(Trade trade)




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:


        public void Explicit_services_are_used_throughout_the_object_graph()


            var theTrade = new Trade();


            IContainer container = new Container(r =>






            Command command = container.With<Trade>(theTrade).GetInstance<Command>();







If you had more than one IView that displayed a Trade object, you could also do this:



        public void pass_explicit_service_into_all_instances()


            // The Container is constructed with 2 instances

            // of TradeView

            var container = new Container(r =>







            Trade theTrade = new Trade();


            var views = container.With<Trade>(theTrade).GetAllInstances<TradeView>();






and have the known Trade object passed into every instance of TradeView.


I’ll post the other way to do this tonight….

About Jeremy Miller

Jeremy is the Chief Software Architect at Dovetail Software, the coolest ISV in Austin. Jeremy began his IT career writing "Shadow IT" applications to automate his engineering documentation, then wandered into software development because it looked like more fun. Jeremy is the author of the open source StructureMap tool for Dependency Injection with .Net, StoryTeller for supercharged acceptance testing in .Net, and one of the principal developers behind FubuMVC. Jeremy's thoughts on all things software can be found at The Shade Tree Developer at
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Guillermo Gutiérrez

    Is there a way to define it in a registry or a container’s configuration, instead of the moment when you are asking for an instance?

  • Matt

    Just the example code I was looking for. Thank you!

  • rubber tracks

    2.5 is not yet released. Jimmy Bogard has labeled it the Duke Nukem Forever release.

    I’ve got to do more docs and clean up the API a touch.

    There will be very minor API changes from 2.4.9 to 2.5 in the registration cat excavator tracks

  • Lisa

    Glad I found this!!

  • Jeff

    Really Nice Thanks!

  • Chris

    Thanks for posting. Really needed this info!

  • icemaker

    It is a very good blog.Thank you for sharing it.

  • icemaker

    It is a very good and informative post ,I like it very much.Thank you for sharing.

  • Kasusr

    We did some do the job in the machine interface amount all around edge detection and things like that to generate it less complicated to possess scaled-down bezels on these gadgets so that office 2010 retail boxOEMs and people who construct products similar to this could build precisely the kinds of gadgets they need, and Windows eight.1 will be good on them.

  • disqus_NYgayD6XyU

    优质资源分享 msdn download , 海盗湾 {etcetera|etc}.

  • Eva Fiskan

    thanks for the infor.
    I’m Eva Fiskan, a supplier for android tablet pc, Android Cellphone, Tablet Pc & Electronics several years.

  • Eva Fiskan

    thanks for the infor.
    I’m Eva Fiskan, a supplier for android tablet pc, Android Cellphone, Tablet Pc & Electronics several years.

  • mens

    Hm. Link did not work – test:

  • mens

    Easier said then done when you are wasting time in college with no job prospects @ no degree

  • menjacket2

    Higher Yoga Physical exercise Physical exercise Pants have Choice of Capabilities Lululemon Canada to Consider into account. Attributed to the Truth Lululemon Wunder Under Pants Yoga Physical exercise

    has a Whole lot of Hard poses and Training routines to do, we ought to be Added Cautious on picking

    the Yoga Physical exercise Physical exercise Pants for us Especially for Higher People who’re Getting Yoga Physical exercise Physical exercise or

    Typical Health club Training routines.

  • ssss

    polo jeans ralph laurenen voici un, je crois. En effet, au bout de la rue de Vaugirard commençait à apparaître le gigantesque Porthos. Quoi. s’écria d’Artagnan, votre premier témoin est M. Porthos Oui, cela vous contrarietil Non, aucunemens. Et voici le second. D’Artagnan se retourna du côté indiqué par Athos. shorts ralph lauren homme
    gilet ralph lauren et reconnut Aramis. Quoi. s’écriatil d’un accent plus étonné que la première fois. votre second témoin est M. Aramis Les mousquetaires du roi et les garde 62 68 Les Trois Mousquetaires Sans doute. ne savezvous pas qu’on ne nous voit jamais l’un sans l’autre. et qu’on nous appelle. Polo Ralph Lauren pas cher Big Pony Polo Ralph Laurendans les mousquetaires et dans les gardes. à la cour et à la ville. Athos. Porthos et Aramis ou les trois inséparables Après cela, comme vous arrivez de Dax ou de Pau De Tarbes. dit d’Artagnan. Il vous est permis d’ignorer ce détail, dit Athos. Ma foi, dit d’Artagnan, vous êtes bien nommés. Chemises Ralph Lauren femme
    68messieurs. et mon aventure. si elle fait quelque bruit, prouvera du moins que votre union n’est point fondée sur les contrastes. Pendant ce temps. Porthos s’était rapproché, avait salué de la main Athos. puis. se retournant vers d’Artagnan, il était resté tout étonné.

  • menjacket2

    With fantastic shades and stylish style, ladies can present your determine and self confidence at when. Men’s The North Face jacket Also different from mens, Moncler jackets for girls more stress about fashionable style, but moncler guys trousers pay more focus to obtain a lot more handsome and mystery feeling. Now extra and extra females are absent of owning a commodity of Moncler clothing. No 1 can low cost The North Face Men’s jacket the actuality of Moncler anorak in your wintertime The North Face Sale planet. So, if you want to keep you elegant and cozy, Moncler Vest Men away from the cold wintertime, get your very own moncler proper now!

  • slip ring

    The slip ring can also be called electric slip ring, rotary connector, electrical rotary joint, collecting ring, electrical slip ring, brush, Moflon slip ring, etc. Dedicated to the unrestricted connecting rotary, transmitting power supply, signal, the stator and the rotor portion, respectively lead wire to connect the power and the electrical terminal of the fixed structure and the rotary structure, and rotation therewith.

  • michaels kors purses

    the Bolivians Section Perez more than a whil. spending two Thousand five hundred dollar. bought the farm here has michael michael kors
    hamilton tote
    been developed, which is “Karami” farm. “Karami farm has one thousand two hundred twenty-seven hectares of land, which is a vast range Wai.However, the farm michael kors outlet online
    residents only one emptying yo premises. It’s near two small towns and village. a is Villag. another Gutierrez Village. In the “Karami emptying it off the premises far, about three kilometers awa. long ago built a A premise. that the past Bolivia local government officials named Ciro Agana Las House.Chuquisaca Camille La

  • chengs

    So buy one Ray Lewis Ravens Jersey in color Home Purple,White Away,Alternate Black to support Him

  • cheap michael kors

    Castro and Nasser met The third part in the Red Star shines Back to Havana, of no fixed abod. state leaders Great gathering of silver michael kors purse rothers Speaking from Khrushchev’s story Soviet Ambassador gained nothing Khrushchev sent a new suitable candidates Khrushchev a coup michael kors handbags on sale outlet Towers Guevara two to Moscow Not eat vegetarian U.S. President J

  • kelevn

    great help, i learned from here a lot, thanks, my site:Cheap Designer Bags

  • shiyaer

    We deal principally in manufacturing and exporting complete flour mill plants and equipments.
    four mill plant

  • JJ Watt Jersey

    Cam Newton was suspended from the team following his confrontation with the police in which he was arrested for burglary, larceny, and obstruction of justice Patrick Willis Jersey. This was 2 many years in the past, now he is in the running for the coveted Heisman trophy. He has produced a total turnaround, Now he plays for Auburn and is lighting it up.
    Cam Newton Stole a Laptop computer Two Years In the pastast J.J. Watt Jersey

    According to the reports, Cam Newton stole a student’s laptop computer worth $1,700, and when he was caught he had thrown in out of his dorm, and then resisted becoming arrested for the exact same Eli Manning Jersey. Because this despicable act, he has cleaned up his life. He has by no means been involved in performing medications or acquiring drunk like lots of athletes succumb to. But in 2008 he was caught with a stolen laptop computer when he was a sophomore, playing for coach Urban Meyer, as element of the University of Florida football program Robert Griffin III Jersey. Cam Newton has considering the fact that then designed very good profession for himself as he stopped having into such random scenarios and straightened himself out Kevin Ogletree Jersey.
    Even Stars Make Problems
    It was not a lengthy time ago when there have been many situations of athletes and players taking steroids for performing much better in the course of an event Ray Rice Jersey, definitely in baseball. Even though those scenarios have decreased, the road to fame and stardom is at times filled with medication and alcohol. There is not a single celebrity star or a superior player of any sport who has not had medicine or gotten extremely drunk at one point or another, and some have also got caught driving under the influence Marshawn Lynch Jersey. DUI lawyers enable persons when they are concerned in conditions that they cannot deal with, specifically when they are caught driving under the influence of medication or alcohol, or when they have had an accident. These days, DUI lawyers have turn out to be a necessity for some effective athletes. DUI lawyers work definitely difficult at what they doVictor Cruz Jersey.
    Digital Age Marketing Group, Inc. is a full service internet marketing firm that prides itself on unparalleled service and performance Arian Foster Jersey. We are committed to providing unbiased internet marketing advice and prudent strategies for growing your business. Our services are always tailored to your unique needs. We provide SEO optimization, sales lead generation, and Google local business center ad placement. Digital Age Marketing Group’s search engine visibility is geared towards driving potential clients to your website. Our unique geographical marketing approach enables us to reach millions of business consumers in record time Clay Matthews Jersey, with a high sale-to-contact ratio. Our reward is satisfied clients!
    So many people going into the 2012 NFL season are already penciling in Cam Newton as one of the best players to turn to in the fantasy football game Aaron Rodgers Jersey. Many feel that as good as he was as a rookie, he will be even better and possibly a top-five quarterback overall.
    Newton does have a lot of positives going for him. The Panthers returned and picked up a lot of talent that they can begin to rely on right away. Troy Polamalu Jersey This is all for a quarterback who was able to pick up over 4000 passing yards and 35 total touchdowns on the ground and through the air.

    Many people expect him to simply match those numbers this year, with perhaps a slight bump. What happens though if he completely surpasses expectations and enters the Brees Peyton Manning Jersey, Brady and Rodgers tier of quarterbacks in the NFL?
    The one think he brings to a fantasy football game that those do not is his legs Rashard Mendenhall Jersey. Even if he does not have the arm to really compete with them, he will always have his legs to rely on. That alone should help him pick up some cheap red zone touchdowns on the ground.
    Defenses will be looking for ways to stop Newton in year two Dez Bryant Jersey, but that is easier said than done. He has a variety of skills that make him hard to contain, even if the defenses are designed to do so.
    Taking him too early might be a risk if you are wanting to set the tone in your fantasy football game. He is great, but he still has a few too many variables when it comes to taking him higher than fifth in your draft. He is going to be a solid option Wes Welker Jersey, you just do not want to end up reaching for him for no good reason.
    Cam Newton impressing teammates Cam Newton sweated through a workout together with his brand-new Carolina teammates Friday morning hours, Carolina Panthers jerseys hopped your flight to help Washington in order to reach obama while in the daytime DeSean Jackson Jersey, and then rapidly went back to make certain your dog went to the last player-organized training Thurs.
    Russell Wilson Jersey Since the Heisman Trophy winner conditions for that inspection for being the NFL’s Absolutely no. One particular over-all select, his / her work mentality, health and enthusiasm to suit with usually are impressing her frequent teammates Cam Newton Jersey. "He showed up on a daily basis first. He could be working hard,In Panthers linebacker Jon Beason stated Friday. "He’s interacted perfectly and also he or she is displayed some good management.In
    Jason Pierre-Paul Jersey
    Newton is generating the best of an offseason including not any other because of the lockout Andrew Luck Jersey.
    This individual cannot talk to Carolina’s innovative education workers. He has forced to find out the playbook by himself. This individual does not have a contract. It can be not sure in the event leading receiver Ken Henderson might be his teammate. There isn’t a indication just how long of your preseason you will see.
    Nevertheless Newton is definitely the factor to regardless of if Tim Tebow Jersey the NFL-worst Panthers may say.
    Newton, who seem to brought about Auburn towards the 2010 and beyond nationwide title using a stunning 50-touchdown year Rob Gronkowski Jersey, will be upbeat along with assured even while he or she acknowledges this American footbal seriously isn’t college football games.
    "Preparing like a quarterback inside the American footbal is utterly unique,Inches he explained. "The words, the particular blitz strategies, as well as the end for the day, you’re not playing freshmen any more. You’re actively playing grown guys Tom Brady Jersey. This is how speed is always.In .
    Newton surely could obtain a playbook plus talk with Carolina’s motor coachs the day following 1st rounded on the draft, if your lockout appeared to be in the short term put. He was quoted saying bad planner Take advantage of Chudzinski provided your pet many "focus factors Frank Gore Jersey." He could be likewise achieved by using previous season’s starter, Jimmy Clausen, to compare and contrast notes.
    Clausen and also free-agent QB He Moore also joined your routines the past two weeks at the Charlotte now senior high school. "I imagine I own a grip with that we have been as being an the offense Michael Vick Jersey, exactly what coach Chudzinski is trying to complete,In Newton claimed.
    Newton thinks the actual Panthers Luke Kuechly Jersey, exactly who monitored Sixteen bothersome touchdowns throughout proceeding 2-14 past time of year, is capable of turning items about, although he is not going to help make every vivid terms regarding conquering out and about Clausen with the starting off occupation Joe Flacco Jersey. Newton the expertise your felony provides viewable in the seven days of workouts "something being frightened of.Inches
    Carolina Panthers are glad to recruit Cam Newton and see him putting on Carolina Panthers Brian Orakpo Jersey. following putting on Carolina Panthers customized NFL Jerseys, Cam Newton will undoubtedly strengthen Panthers and display his expertise as quarterback. Cam Newton is somebody who discovered the endzone at Auburn like it experienced been a bodily purpose and rode that to some Heisman Trophy and also a country 2012 World Series Tim Lincecum Jersey wide championship in a single period using the Tigers.2012 World Series Buster Posey Jersey………

  • mali

    I agree with you. taobao agent

  • weaponfan

  • sachin ruhela

    Access File Repair
    access password recovery
    Access Password Recovery Software
    MS Access Password Recovery
    Access Password Recovery Tool
    Fix Excel
    download free key logger
    Chat Archive Recovery
    Database conversion software
    MS excel repair software
    Data Recovery Tool
    Web Hosting
    Free Data Wiper
    Digital camera photo recovery software
    Disk Recovery Software
    Data recovery software free download
    Database Converters
    Free Keylogger
    Excel File Recovery
    MS Access Password Recovery Tool
    Excel Recovery
    free keylogger software
    Floppy Recovery
    Repair Excel
    Excel Repair
    recover msn password
    Excel File Fix
    Floppy Disk Recovery
    Windows Data Recovery
    Keystroke Logger
    Hard drive data recovery
    Free Excel Recovery
    Windows Recovery Tools
    IE Password Recovery
    IPod Recovery
    Key logger
    Excel Recovery Tool
    download a free keylogger
    keyloggers free
    keylogger freeware
    Keylogger Spy Software
    keylogger software free
    keystroke capture
    Recovery Password
    free keylogger downloads
    best keylogger free
    msn password recovery
    Outlook Express Password Recovery Software
    password finder
    Keylogger Software Download
    Password Recovery
    password recovery software
    password recovery software free
    pen drive data recovery software
    Pen Drive Recovery
    PowerPoint Repair Tool
    Chat Recovery Software
    Fix Excel File
    Restore Excel File
    Email Recovery
    cell phone sms recovery software
    recovery for excel
    Repair Excel Files
    repair excel files software
    Data Recovery Software
    sim card deleted sms recovery
    SIM Card Data Recovery
    Key logger software
    downloadable keylogger
    download keylogger freeware
    free invisible keylogger
    data recovery
    Download Free Keylogger
    keystroke recorder
    software keylogger
    remote key logger
    sim recovery
    Sim Card Recovery
    Backlinks Checker Tool
    remote keylogger free
    Spy Keylogger
    USB drive data recovery
    Free Backlink Finder Tool
    Zip Repair Tool
    Data recovery software for NTFS
    Recovery Format Data
    Partition recovery software
    Backlinks Checker
    Sim Card SMS Recovery
    Word file repair software
    data recovery services

    Is good for this post. Your blog is very interesting and great information, thanks

  • David Hayden

    Thanks for the info, Jeremy!

    Looking forward to the final release.

  • Jeremy D. Miller


    2.5 is not yet released. Jimmy Bogard has labeled it the Duke Nukem Forever release.

    I’ve got to do more docs and clean up the API a touch.

    There will be very minor API changes from 2.4.9 to 2.5 in the registration

  • David Hayden


    Has 2.5 been released yet? I keep seeing reference to 2.5 but only see 2.4.9 for download. Just want to make sure I am not using old bits. Hopefully 2.4.9 is production deployable because deployed she is :)

  • Jeremy D. Miller


    I was thinking much more in general than DDD in terms of “anything you would not want to new() up directly.:

    Not that you could have possibly known this, but the staggering amount of jargon in DDD is a huge pet peeve of mine.

    “Domain Service” vs “Application Service” might have some useful differentiation, but the jargon still bugs me.

    “Case in point: Suppose you had a really complicated interest calculation mechanism in your LoanAccount entity and you wanted to use the same mechanism in your InterestAccount entity, wouldn’t it make sense to inject the service into both in order to “stay DRY”.”

    I wouldn’t bother with SM for this kind of thing. Just pass the LoanAccount and InterestAccount into the domain service as it’s invoked is my bet.

  • Jonathan

    When you refer to a “service”, you’re talking about an “Application Service”, right? Per my reading of Evan’s DDD a “Domain Service” is just as much a part of the domain as anything else and can be called from within the domain “core”.

    Case in point: Suppose you had a really complicated interest calculation mechanism in your LoanAccount entity and you wanted to use the same mechanism in your InterestAccount entity, wouldn’t it make sense to inject the service into both in order to “stay DRY”.

  • Torkel

    This is a really useful feature, I discovered it (and the need for it) a while ago in Castle Windsor.