This question is answered fairly elegantly in the following SO post:
StructureMap CacheBy InstanceScope.HttpSession not working
Essentially, the magic comes from the following code (adapted for your question and the newer syntax for StructureMap
):
ObjectFactory.Initialize(factory => {
factory.For<MyContext>()
.CacheBy(InstanceScope.HttpSession)
.Use(new MyContext(_myConnectionString));
});
Then - in your controller, simply create an instance of the object by using:
var db = ObjectFactory.GetInstance<MyContext>();
Because your IoC (Inversion of Control) set-up via StructureMap
has configured the instances to be scoped to HttpSession
, you should retrieve the same context each time as long as the session is the same.
However - bear in mind that with DbContext
objects, in particular, this is usually a very poor idea - as you are mixing a state-tracking object with a stateless environment, and can easily get yourself into a state where a bad transaction or an object which is in an odd state can stop you from doing any further database calls until you refresh your session.
DbContext
objects are generally designed to be extremely lightweight and disposable. It's fully ok to let them drop out of scope and die basically as soon as you're done with them.