StructureMap and Dapper: Scoping and Lifecycle

March 12, 2014 mgroves 47 comments
Tags: dapper structuremap IoC asp.net mvc

In a project that I'm working on, I'm using Dapper for data access and I'm using StructureMap as my IoC containter. It's an ASP.NET MVC project.

I was recently demoing the project to my partner on the staging site (Azure), and I ran into a troubling error having to do with data connections (that I had not experienced running it locally on IIS yet). I immediately thought that it must be an issue with the SQL connections (SqlDbConnection objects that implement the IDbConnection interface, per Dapper) not being closed and/or disposed of correctly.

I remember encountering the same issue when I was developing this very site that you are reading, and the solution is to use the HttpContext scope within StructureMap when configuring it for the IDbConnection interface.

Here's what I started with:

And here's what I refactored it to:

I just added HttpContextScoped (the default is PerRequest scope, see StructureMap docs on Scoping and Lifecycle Management). I also added the ReleaseAndDisposeAllHttpScopedObjects to Global.asax.cs, so that StructureMap would...release and dispose those objects at the end of each request.

However, when I did that, I was still getting problems. I would get exceptions saying that the SqlConnection ConnectionString was the empty string. Something wasn't right. I did some searching around about the issue in the docs, and couldn't really find what I was looking for. I did come across someone with a similar issue on StackOverflow, also trying to understand HttpContextScoped. The top answer from PHeiberg (not the accepted answer) pointed me the right direction.

I used a lambda expression instead of just passing the SqlConnection directly. So now my SqlDbConnections are scoped to the HttpContext, and will be cleaned up after every request. That should squash the issue I was seeing on the staging stie.

Comments

Avatar for Simon C

Posted by Simon C on March 11, 2015

Perfect, just what I was after :)

Avatar for mgroves

Posted by mgroves on March 20, 2015

Glad you found it useful. If you're using a newer version of StructureMap, check out some of the related changes: https://crosscuttingconcerns.azurewebsites.net/StructureMap-3---some-changes-Ive-noticed

Avatar for cursos verano upv 2013 bizkaia

Posted by cursos verano upv 2013 bizkaia on February 02, 2016

El campamento tuvo como temática La Prehistoria”.

Avatar for Luxury Beauty

Posted by Luxury Beauty on February 02, 2016

It's going to be finish of mine day, except before ending I am reading this great piece of writing to improve my experience.

Avatar for daily success deals

Posted by daily success deals on February 02, 2016

What i don't understood is actually how you are now not really a lot more neatly-appreciated than you might be now. You are so intelligent.

You realize thus significantly relating to this topic, made me in my view consider it from so many various angles. Its like women and men are not interested until it's one thing to accomplish with Girl gaga! Your individual stuffs great. All the time deal with it up!

Avatar for insurance auto Auctions houston

Posted by insurance auto Auctions houston on February 02, 2016

Hey , very same factor happened to me , I am so upset, I wonder if I get my money back.

Avatar for www.insermed.es

Posted by www.insermed.es on February 02, 2016

Just beneficial data is provided by this blog and that I am checking to it this instant! Thankyou people!

Avatar for Best Air Conditioning Overland Park KS

Posted by Best Air Conditioning Overland Park KS on February 02, 2016

This web site provides only useful data and that I am checking to it this instant! Thanks guys!

Avatar for codes de triches les sims 4

Posted by codes de triches les sims 4 on February 02, 2016

Even in this fictitious globe resources are restricted and you will have to find a job for the sims day to day life.

Avatar for Healthy sex drive

Posted by Healthy sex drive on February 02, 2016

Fantastic beat ! I wish to apprentice whilst you amend your website, how can i subscribe for a weblog site? The account aided me a applicable deal. I were a little bit acquainted of this your broadcast offered brilliant transparent idea

Avatar for legal resource

Posted by legal resource on February 02, 2016

When some one searches for his required thing, therefore he/she wants to be available that in detail, therefore that thing is maintained over here.

Avatar for ??? ??

Posted by ??? ?? on February 02, 2016

Hello my friend! I want to say that this post is awesome, great written and come with approximately all important infos. I'd like to look more posts like this .

Avatar for Best Interior Designer Singapore

Posted by Best Interior Designer Singapore on February 02, 2016

It's remarkable to pay a visit this website and reading the views of all mates on the topic of this article, while I am also eager of getting experience.

Avatar for caalp.es

Posted by caalp.es on February 02, 2016

I needed to take some time expressing my passion towards you and also this website that was amazing! Caring it!

Avatar for Humberto

Posted by Humberto on February 03, 2016

I am truly pleased to glance at this web site posts which consists of plenty of useful data, thanks for providing these kinds of data.

Avatar for speleokamera.com

Posted by speleokamera.com on February 03, 2016

Famous siblings Kim and also Khloe have sustained plenty of interest in this fad, by posting Instagram pictures of themselves in current months putting on waist-training tools-- essentially, bands of product that cover tightly around the waist as well as lower rib cage to supply an instantaneously slendering, shapely appearance.

Avatar for www.goldenleadsgr.com

Posted by www.goldenleadsgr.com on February 03, 2016

I am actually happy to read this website posts which consists of tons of helpful information, thanks for providing these kinds of information.

Avatar for linwed.dothome.co.kr

Posted by linwed.dothome.co.kr on February 03, 2016

Hello to all, as I am truly eager of reading this webpage's post to be updated on a regular basis. It includes nice information.

Avatar for patio umbrella amazon

Posted by patio umbrella amazon on February 03, 2016

This web site offers only beneficial information and that I am subscribing to it-this instant! Thank you folks!

Avatar for beat generals videos download

Posted by beat generals videos download on February 03, 2016

Thanks for your marvelous posting! I actually enjoyed reading it, you may be a greeat author.I wwill make certain to bookmark your blog and definitey will come back in tthe foreseeable future. I wwant to encourage yourseelf to continue your great work, have a nice morning!

Avatar for Bev

Posted by Bev on February 03, 2016

Thanks for finally writing about >StructureMap and Dapper: Scoping and Lifecycle | Cross Cutting Concerns

Avatar for website

Posted by website on February 03, 2016

I was recommended this blog via my cousin. I'm no longer sure whether this post is written by way of him as nobody else realize such designated approximately my trouble. You are incredible! Thank you!

Avatar for semena marihuany

Posted by semena marihuany on February 03, 2016

What's up Dear, are you really visiting this site daily, if so after that you will without doubt take fastidious knowledge.

Avatar for http://www.ellegance.ca/

Posted by http://www.ellegance.ca/ on February 03, 2016

If some one needs expert view regarding blogging and site-building afterward i propose him/her to go to see this weblog, Keep up the nice work.

Avatar for Lanny

Posted by Lanny on February 03, 2016

I was hoping that after it tripped zero that this thread could just stop but I guess that is just hopeful thinking. I guess next time.

Avatar for fox42kptm.com

Posted by fox42kptm.com on February 03, 2016

For latest information you have to pay a visit the web and on world-wide-web I found this web site as a best web page for newest updates.

Avatar for www.tothpaszomany.hu

Posted by www.tothpaszomany.hu on February 03, 2016

Admiring the time and effort you put into your website and in depth information you offer. It's awesome to come across a blog every once in a while that isn't the same outdated rehashed information. Great read! I've bookmarked your site and I'm including your RSS feeds to my Google account.

Avatar for www.purpurastore.com.co

Posted by www.purpurastore.com.co on February 04, 2016

Can I simply just say what a comfort to discover somebody who truly knows what they are discussing on the net. You definitely realize how to bring an issue to light and make it important. A lot more people have to read this and understand this side of the story.

I can't believe you aren't more popular because you surely possess the gift.

Avatar for Singapore Interior Designer

Posted by Singapore Interior Designer on February 04, 2016

I'm amazed, I must say. Seldom do I come across a blog that's equally educative and amusing, and without a doubt, you've hit the nail on the head. The issue is something too few people are speaking intelligently about. I'm very happy I came across this during my search for something concerning this.

Avatar for Www.maxgalkin.ru

Posted by Www.maxgalkin.ru on February 04, 2016

I did some research and dug deep right into as high as i might find on the internet and the outcomes were looked like there was not enough info around on waistline training.

Avatar for latex socks

Posted by latex socks on February 04, 2016

Hi my friend! I wish to say that this article is amazing, nice written and come with almost all significant infos. I'd like to look extra posts like this .

Avatar for 24 hour bond

Posted by 24 hour bond on February 04, 2016

Can I simply say what a relief to uncover somebody that actually understands what they are discussing over the internet. You actually understand how to bring an issue to light and make it important. A lot more people need to check this out and understand this side of your story. I can't believe you're not more popular given that you most certainly possess the gift.

Avatar for Black Slate Reggae band

Posted by Black Slate Reggae band on February 04, 2016

I think this is one of the so much significant information for me. And i am satisfied studying your article. But should observation on some common issues, The website taste is great, the articles is really great : D. Just right job, cheers

Avatar for Goblins Quest 3 do pobrania

Posted by Goblins Quest 3 do pobrania on February 04, 2016

When some one searches for his vital thing, so he/she desires to be available that in detail, therefore that thing is maintained over here.

Avatar for TY the Tasmanian Tiger 4 poradnik

Posted by TY the Tasmanian Tiger 4 poradnik on February 04, 2016

Great beat ! I wish to apprentice even as you amend your site, how could i subscribe for a blog web site? The account aided me a appropriate deal. I were a little bit familiar of this your broadcast provided vivid clear concept

Avatar for chemistry

Posted by chemistry on February 05, 2016

Pretty nice post. I simply stumbled upon your blog and wanted to say that I have truly enjoyed surfing around your blog posts. After all I'll be subscribing in your rss feed and I hope you write again very soon!

Avatar for Symulator zamiatarki ulic crack

Posted by Symulator zamiatarki ulic crack on February 05, 2016

Can I simply just say what a comfort to find someone that truly knows what they're talking about on the net. You actually know how to bring a problem to light and make it important. More and more people have to read this and understand this side of the story. It's surprising you're not more popular given that you certainly have the gift.

Avatar for Bed and Breakfast

Posted by Bed and Breakfast on February 05, 2016

What i don't understood is in fact how you are no longer really much more well-appreciated than you might be now. You are very intelligent. You already know therefore significantly on the subject of this topic, produced me for my part consider it from so many various angles. Its like men and women aren't involved unless it is something to accomplish with Lady gaga! Your own stuffs outstanding. At all times maintain it up!

Avatar for craigslist flagging tool

Posted by craigslist flagging tool on February 05, 2016

Hi there everyone, it's my first go to see at this web page, and paragraph is genuinely fruitful in support of me, keep up posting such posts.

Avatar for Rapid Loans USA Trial

Posted by Rapid Loans USA Trial on February 05, 2016

What's up to every single one, it's really a fastidious for me to visit this web site, it contains priceless Information.

Avatar for best email autoresponder

Posted by best email autoresponder on February 05, 2016

Now I am going away to do my breakfast, later than having my breakfast coming again to read more news.

Avatar for Lavada

Posted by Lavada on February 05, 2016

Very quickly this site will be famous amid all blogging and site-building viewers, due to it's good articles

Avatar for Mamie

Posted by Mamie on February 05, 2016

fantastic issues altogether, you just won a emblem new reader.

What might you suggest in regards to your publish that you simply made some days in the past? Any positive?

Avatar for Don Grisley

Posted by Don Grisley on February 05, 2016

Thank you for the auspicious writeup. It in truth was a leisure account it. Glance complex to far delivered agreeable from you! However, how can we keep in touch?

Avatar for Infinite Binary Profit Code

Posted by Infinite Binary Profit Code on February 05, 2016

What i don't realize is actually how you are not actually a lot more neatly-appreciated than you may be now. You are very intelligent.

You already know thus significantly in relation to this topic, produced me in my view believe it from so many numerous angles. Its like men and women don't seem to be interested except it is something to do with Woman gaga! Your individual stuffs nice. All the time deal with it up!

Avatar for Patrician III Rise of the Hanse spolszczenie

Posted by Patrician III Rise of the Hanse spolszczenie on February 05, 2016

I leave a response each time I like a article on a site or I have something to valuable to contribute to the conversation. It's caused by the passion displayed in the article I looked at. And after this article StructureMap and Dapper: Scoping and Lifecycle | Cross Cutting Concerns. I was actually moved enough to drop a thought : -P I do have a couple of questions for you if you tend not to mind. Could it be just me or do some of these comments come across like they are written by brain dead individuals? :-P And, if you are posting at other sites, I would like to keep up with anything new you have to post.

Could you list all of your community pages like your linkedin profile, Facebook page or twitter feed?

Avatar for hand drill auger bits for soil

Posted by hand drill auger bits for soil on February 06, 2016

I am sure this article hass touched all the internet viewers, its really really nice paragraph on building up new webpage.

Leave a Comment

*
*
Some HTML will be escaped, you can use StackOverflow-flavored Markdown
Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter