0

I am trying to figure out how to setup a StructureMap3 configuration, that works in both a WebApi and in a Console application, like:

For<ISession>().HybridHttpOrThreadLocalScoped().Use(p => p.GetInstance<TestingContainer>().GetSession());

For console apps I would like the object to live as long as the thread lives, and for websites as long as the http-session lives.

This is possible with MVC websites because HybridHttpOrThreadLocalScoped use the HttpSessionState to determine whether to create a new instance or to reuse an existing instance.

WebApi doesn't have this HttpSessionState and therefore HybridHttpOrThreadLocalScoped won't work.

If I didn't care about the console app, then I would probably configure structuremap with Transient() or AlwaysUnique or similar.

So, what is the equivalent to HybridHttpOrThreadLocalScoped when there are no HttpSessionState instance.

Thank you.

EDIT

-to rearrange the question...

1 Answers1

0

In general you should favor Nested Containers for lifecycle management. The reasons behind this are exactly what you've just noted, that in some situations using either Thread, HTTP, or hybrid scoped simply doesn't work. I've seen it cause huge issues before where people assume DB connections are being disposed because they are in other environments, but in one environment they aren't. Also, the explicitness is nice.

To do this set the dependencies you want disposed per request to Transient (the default) and dispose of the nested container at the end of the request. I've written about this workflow in webapi here. Additionally the official docs recommend this nuget.

For the console app you'll want to do something like this:

//parent Container set up at app start
public void On_UserAction()
{
    //global container set up at app start, either use ObjectFactory (bad, deprecated and to be removed) or just keep track of it yourself.
    using(var nestedContainer = GlobalContainer.GetNestedContainer())
    {
        var dependency = nestedContainer.GetInstance<DependencyThatHandlesUserInput>();
    }
}

and that's it, the using block handles all the disposal for you.

If you have any other questions please ask, I've spent a lot of time on this sort of thing :).

JCalder
  • 391
  • 3
  • 8
  • In a way, I agree with your logic, but what happens if you create two threads within the same nested container? I guess we don't want a dependency between the nested container and a thread, where we must remember to created a new nested container for each new thread, or.... ? – Peter Larsen 'CPH' Oct 27 '15 at 10:56