In StructureMap, how can I change InstanceScope at runtime?

In my DefaultRegistry, I have this configuration:

ForRequestedType<INHUnitOfWork>().CacheBy(InstanceScope.HttpContext)
        .TheDefault.Is.OfConcreteType<NHibernateUnitOfWork>();

      

At some point in the web application thread, I want to change InstanceScope to HttpSession to get a long conversation, so I do this:

PluginTypeConfiguration config = ObjectFactory.Model.PluginTypes.FirstOrDefault(p => p.PluginType.FullName.Contains("INHUnitOfWork"));
config.Lifecycle.EjectAll();
config.Lifecycle = StructureMap.Pipeline.Lifecycles.GetLifecycle(InstanceScope.HttpSession);

      

This seems to replace the original InstanceScope instance, unfortunately it only lasts for the current request. When the next request comes in, the initial configuration is reactivated and the session information is lost.

Later, I also want to be able to revert to the following:

PluginTypeConfiguration config = ObjectFactory.Model.PluginTypes.FirstOrDefault(p => p.PluginType.FullName.Contains("INHUnitOfWork"));
config.Lifecycle.EjectAll();
config.Lifecycle = StructureMap.Pipeline.Lifecycles.GetLifecycle(InstanceScope.HttpContext);

      

but if I make it work in one direction, it will probably work in both.

Is it possible to replace the original InstanceScope instance with a runtime time? How should this be done? Also, do you think this is a good way to get a long conversation, or is there a better / easier way to do this with StructureMap and NHibernate?

+1


a source to share


2 answers


Take a look at Ayende's detailed explanation on how to enable long conversations and UnitOfWork:

http://ayende.com/Wiki/Default.aspx?Page=HttpModules & AspxAutoDetectCookieSupport = 1



I would recommend creating a UnitOfWorkApplication module and being responsible for instantiating UnitOfWork and adding it to the container before your code is executed (before processing the request like in the example). This way you have more flexibility and control over how you create a unit of work.

+1


a source


It seems a bit strange to me what you are trying to do. The routes I would try would be

  • Set up a named instance in a StructureMap that also implements the specified interface but has different scopes. You can introduce different dependencies for different users of the interface, maybe it helps?
  • Write your own CacheInterceptor that effectively implements your specific lifecycle.


The latter is done, for example. here for WCF lifecycle: http://blogs.rpionline.com/post/2009/02/How-to-use-NHibernate-and-StructureMap-in-a-WCF-application.aspx

0


a source







All Articles