tags:

views:

204

answers:

1

I have this object "mySessionObject" of type "SessionObject". It implements the interfaces IMessageHandler<MessageA> and IMessageHandler<MessageB>. I should only have one of these objects, and it should live thru the entire HttpSession.

How do I register it with structuremap so that I at any time in the lifetime of the HttpSession can get it by calling ObjectFactory.GetInstance<IMessageHandler<MessageA>>(), or ObjectFactory.GetInstance<IMessageHandler<MessageB>>() ?

A: 

Inside of your normal StructureMap configuration, I would add this code:

ObjectFactory.Initialize(x =>
{
    x.ForRequestedType<IMessageHandler<MessageA>>().
        TheDefaultIsConcreteType<MyImplementingClass>().
        CacheBy(InstanceScope.HttpSession);

    x.ForRequestedType<IMessageHandler<MessageB>>().
        TheDefaultIsConcreteType<MyImplementingClass>>().
        CacheBy(InstanceScope.HttpSession);});
}

Note that you will need the 2.5.3 StructureMap release as detailed in this SO thread: http://stackoverflow.com/questions/497564/structuremap-cacheby-instancescope-httpsession-not-working

I'm away from a compiler at the moment, but I believe that CacheBy is smart enough to share objects between implementing classes. If not, you can construct a MyImplementingClass another way, and then use TheDefaultIs() rather than TheDefaultIsConcreteType().

CitizenParker