<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://nhforge.org/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>CurrentSessionContext for Desktop development</title><link>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development.aspx</link><description>Quick starts, tutorials, code snippets, custom user types, application blocks and more...</description><dc:language>en-US</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>CurrentSessionContext for Desktop development</title><link>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development.aspx</link><pubDate>Fri, 06 Nov 2009 19:07:57 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:68</guid><dc:creator>Jason Meckley</dc:creator><comments>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/comments.aspx</comments><description>Current revision posted to How to by Jason Meckley on 06/11/2009 04:07:57 p.m.&lt;br /&gt;
&lt;h2&gt;CurrentSessionContext for Desktop development&lt;/h2&gt;
&lt;div style="font-size: 90%;"&gt;Filed under: &lt;span style="text-decoration: line-through; color: red;"&gt;Session&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;CurrentSessionContext&lt;/span&gt;, IoC container, &lt;span style="text-decoration: line-through; color: red;"&gt;CurrentSessionContext&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;Session&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;I have used current session contexts in web applications with the ManagedWebContext class. I wanted to get this working in a non-asp.net environment though. And I wanted to keep the UI responsive, which means pushing as much as possible to the background.&amp;nbsp; I took a queue from Jeremy Miller&amp;#39;s article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee309512.aspx"&gt;functional programming&lt;/a&gt;. To that end, here is one approach to managing Sessions in a threaded environment.&lt;/p&gt;
&lt;p&gt;we will utilize the typical MVP triad injecting our view into the presenter.&lt;/p&gt;
&lt;pre&gt;    public class Presenter : IPresenter
    {
        private readonly IView view;
        private readonly IService service;
        private readonly ICommandExecutor executor;

        public Presenter(IView view, IService service, ICommandExecutor executor)
        {
            this.view = view;
            this.service = service;
            this.executor = executor;
        }

        public virtual void UpdateView()
        {
            executor.Execute(() =&amp;gt;
                                 {
                                     var text = service.GetData(1);
                                     return () =&amp;gt; view.UpdateUserInterface(text);
                                 });
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;So what is the ICommandExecutor? This is where we centralize threading and session management. For SoC I have devided this into 2 implementations. one for threading the other for session management.&lt;/p&gt;
&lt;pre&gt;    public class AsynchronousExecutor : ICommandExecutor
    {
        private readonly SynchronizationContext synchronizationContext;
        private readonly ICommandExecutor executor;

        public AsynchronousExecutor(SynchronizationContext synchronizationContext, ICommandExecutor executor)
        {
            this.synchronizationContext = synchronizationContext;
            this.executor = executor;
        }

        public void Execute(Action action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(action));
        }

        public void Execute(Func&amp;lt;Action&amp;gt; action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(() =&amp;gt;
                        {
                           var continuation = action();
                           synchronizationContext.Send(x =&amp;gt; continuation(), null);
                        }));
        }
    }

    public class UnitOfWorkExecutor : ICommandExecutor
    {
        private readonly ISessionFactory factory;

        public UnitOfWorkExecutor(ISessionFactory factory)
        {
            this.factory = factory;
        }

        public void Execute(Action action)
        {
            ExecuteWithinAUnitOfWork(action);
        }

        public void Execute(Func&amp;lt;Action&amp;gt; action)
        {
            ExecuteWithinAUnitOfWork(() =&amp;gt; action());
        }

        private void ExecuteWithinAUnitOfWork(Action action)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    CurrentSessionContext.Bind(factory.OpenSession());
                    action();
                    transaction.Complete();
                }
            }
            finally
            {
                var session = CurrentSessionContext.Unbind(factory);
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;AsynchronousExecutor pushes work to the background while UnitOfWorkExecutor sets up the context of a session. For information on synchronizationContext I will defer you to Jeremy&amp;#39;s MSDN article. 2 steps left. 1) Configure NH and 2) wire this together.&lt;/p&gt;
&lt;p&gt;To configure NH we will use Fluent NHibernate. The important part is setting the CurrentSessionContext property. For those not using programmatic configuration, you would set the property in the hibernate.config file along with the other session factory configs.&lt;/p&gt;
&lt;p&gt;For wiring I&amp;#39;m using Castle Windsor. Any IoC should allow for something similar though. after placing the configuration and factory in the kernel we can use a factory method to resolve the session from the kernel. Note that the lifestyle of session is Transient. this is crucial, otherwise the sessions will not resolve correctly. We will use the same technique for resolving the SynchronizationContext as well.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;    public class NHibernateFacility : AbstractFacility
    {
        protected override void Init()
        {
            var configuration = Fluently
                .Configure()
                .Database(() =&amp;gt; MsSqlConfiguration.MsSql2000)
                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssembly(GetType().Assembly))
                .ExposeConfiguration(ExtendConfiguration)
                .BuildConfiguration();

            Kernel.AddComponentInstance(&amp;quot;configuration&amp;quot;, configuration);
            Kernel.AddComponentInstance(&amp;quot;factory&amp;quot;, configuration.BuildSessionFactory());
            Kernel.Register(Component
                                .For&amp;lt;ISession&amp;gt;()
                                .LifeStyle.Is(LifestyleType.Transient)
                                .UsingFactoryMethod(k =&amp;gt; &lt;span style="text-decoration: line-through; color: red;"&gt;k.Resolve&lt;/span&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;ISessionFactory&amp;gt;().GetCurrentSession()));&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;k&lt;/span&gt;&lt;br /&gt;                                             &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;Resolve&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;ISessionFactory&amp;gt;()&lt;/span&gt;&lt;br /&gt;                                             &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;GetCurrentSession()));&lt;/span&gt;
        }

        private static void ExtendConfiguration(Configuration cfg)
        {
            &lt;span style="background: SpringGreen;"&gt;var&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;context&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;=&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;typeof(ThreadStaticSessionContext).AssemblyQualifiedName&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;&lt;br /&gt;           &amp;nbsp;cfg.SetProperty(Environment.CurrentSessionContextClass, &lt;span style="text-decoration: line-through; color: red;"&gt;typeof(ThreadStaticSessionContext).AssemblyQualifiedName)&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;context)&lt;/span&gt;;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we wire up the entire container.&lt;/p&gt;
&lt;pre&gt;    internal static class Program
    {
        private static IWindsorContainer container;

        [STAThread]
        private static void Main()
        {
            container = new WindsorContainer()
                .AddFacility&amp;lt;FactorySupportFacility&amp;gt;()
                .AddFacility&amp;lt;NHibernateFacility&amp;gt;()
                .AddComponentLifeStyle&amp;lt;ICommandExecutor, AsynchronousExecutor&amp;gt;(LifestyleType.Singleton)
                .AddComponentLifeStyle&amp;lt;ICommandExecutor, UnitOfWorkExecutor&amp;gt;(LifestyleType.Singleton)
                .AddComponentLifeStyle&amp;lt;MainForm&amp;gt;(LifestyleType.Transient)
                .AddComponentLifeStyle&amp;lt;IPresenter, Presenter&amp;gt;(LifestyleType.Transient)
                .AddComponentLifeStyle&amp;lt;IService, Service&amp;gt;(LifestyleType.Transient)
                .Register(Component
                              .For&amp;lt;SynchronizationContext&amp;gt;()
                              .LifeStyle.Is(LifestyleType.Singleton)
                              .UsingFactoryMethod&amp;lt;SynchronizationContext&amp;gt;(CreateSynchronizationContext));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(container.Resolve&amp;lt;MainForm&amp;gt;());
        }

        private static SynchronizationContext CreateSynchronizationContext()
        {
            if (SynchronizationContext.Current == null)
            {
                &lt;span style="text-decoration: line-through; color: red;"&gt;SynchronizationContext.SetSynchronizationContext(new&lt;/span&gt; &lt;span style="text-decoration: line-through; color: red;"&gt;WindowsFormsSynchronizationContext())&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;var&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;context&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;=&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;new&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;WindowsFormsSynchronizationContext()&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;&lt;br /&gt;               &amp;nbsp;&lt;span style="background: SpringGreen;"&gt;SynchronizationContext.SetSynchronizationContext(context)&lt;/span&gt;;&lt;br /&gt;            }&lt;br /&gt;            return SynchronizationContext.Current;&lt;br /&gt;        }&lt;br /&gt;    }&lt;/pre&gt;</description></item><item><title>CurrentSessionContext for Desktop development</title><link>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/revision/3.aspx</link><pubDate>Fri, 06 Nov 2009 19:04:59 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:297</guid><dc:creator>Jason Meckley</dc:creator><comments>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/comments.aspx</comments><description>Revision 3 posted to How to by Jason Meckley on 06/11/2009 04:04:59 p.m.&lt;br /&gt;
&lt;h2&gt;CurrentSessionContext for Desktop development&lt;/h2&gt;
&lt;div style="font-size: 90%;"&gt;Filed under: Session, IoC container, CurrentSessionContext&lt;/div&gt;

&lt;p&gt;I have used current session contexts in web applications with the ManagedWebContext class. I wanted to get this working in a non-asp.net environment though. And I wanted to keep the UI responsive, which means pushing as much as possible to the background.&amp;nbsp; I took a queue from Jeremy Miller&amp;#39;s article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee309512.aspx"&gt;functional programming&lt;/a&gt;. To that end, here is one approach to managing Sessions in a threaded environment.&lt;/p&gt;
&lt;p&gt;we will utilize the typical MVP triad injecting our view into the presenter.&lt;/p&gt;
&lt;pre&gt;    public class Presenter : IPresenter
    {
        private readonly IView view;
        private readonly IService service;
        private readonly ICommandExecutor executor;

        public Presenter(IView view, IService service, ICommandExecutor executor)
        {
            this.view = view;
            this.service = service;
            this.executor = executor;
        }

        public virtual void UpdateView()
        {
            executor.Execute(() =&amp;gt;
                                 {
                                     var text = service.GetData(1);
                                     return () =&amp;gt; view.UpdateUserInterface(text);
                                 });
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;So what is the ICommandExecutor? This is where we centralize threading and session management. For SoC I have devided this into 2 implementations. one for threading the other for session management.&lt;/p&gt;
&lt;pre&gt;    public class AsynchronousExecutor : ICommandExecutor
    {
        private readonly SynchronizationContext synchronizationContext;
        private readonly ICommandExecutor executor;

        public AsynchronousExecutor(SynchronizationContext synchronizationContext, ICommandExecutor executor)
        {
            this.synchronizationContext = synchronizationContext;
            this.executor = executor;
        }

        public void Execute(Action action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(action));
        }

        public void Execute(Func&amp;lt;Action&amp;gt; action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(() =&amp;gt;
                                     {
                                             var continuation = action();
                                            synchronizationContext.Send(x =&amp;gt; continuation(), null);
                                    }));
        }
    }

    public class UnitOfWorkExecutor : ICommandExecutor
    {
        private readonly ISessionFactory factory;

        public UnitOfWorkExecutor(ISessionFactory factory)
        {
            this.factory = factory;
        }

        public void Execute(Action action)
        {
            ExecuteWithinAUnitOfWork(action);
        }

        public void Execute(Func&amp;lt;Action&amp;gt; action)
        {
            ExecuteWithinAUnitOfWork(() =&amp;gt; action());
        }

        private void ExecuteWithinAUnitOfWork(Action action)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    CurrentSessionContext.Bind(factory.OpenSession());
                    action();
                    transaction.Complete();
                }
            }
            finally
            {
                var session = CurrentSessionContext.Unbind(factory);
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;AsynchronousExecutor pushes work to the background while UnitOfWorkExecutor sets up the context of a session. For information on synchronizationContext I will defer you to Jeremy&amp;#39;s MSDN article. 2 steps left. 1) Configure NH and 2) wire this together.&lt;/p&gt;
&lt;p&gt;To configure NH we will use Fluent NHibernate. The important part is setting the CurrentSessionContext property. For those not using programmatic configuration, you would set the property in the hibernate.config file along with the other session factory configs.&lt;/p&gt;
&lt;p&gt;For wiring I&amp;#39;m using Castle Windsor. Any IoC should allow for something similar though. after placing the configuration and factory in the kernel we can use a factory method to resolve the session from the kernel. Note that the lifestyle of session is Transient. this is crucial, otherwise the sessions will not resolve correctly. We will use the same technique for resolving the SynchronizationContext as well.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;    public class NHibernateFacility : AbstractFacility
    {
        protected override void Init()
        {
            var configuration = Fluently
                .Configure()
                .Database(() =&amp;gt; MsSqlConfiguration.MsSql2000)
                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssembly(GetType().Assembly))
                .ExposeConfiguration(ExtendConfiguration)
                .BuildConfiguration();

            Kernel.AddComponentInstance(&amp;quot;configuration&amp;quot;, configuration);
            Kernel.AddComponentInstance(&amp;quot;factory&amp;quot;, configuration.BuildSessionFactory());
            Kernel.Register(Component
                                .For&amp;lt;ISession&amp;gt;()
                                .LifeStyle.Is(LifestyleType.Transient)
                                .UsingFactoryMethod(k =&amp;gt; k.Resolve&amp;lt;ISessionFactory&amp;gt;().GetCurrentSession()));
        }

        private static void ExtendConfiguration(Configuration cfg)
        {
            cfg.SetProperty(Environment.CurrentSessionContextClass, typeof(ThreadStaticSessionContext).AssemblyQualifiedName);
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we wire up the entire container.&lt;/p&gt;
&lt;pre&gt;    internal static class Program
    {
        private static IWindsorContainer container;

        [STAThread]
        private static void Main()
        {
            container = new WindsorContainer()
                .AddFacility&amp;lt;FactorySupportFacility&amp;gt;()
                .AddFacility&amp;lt;NHibernateFacility&amp;gt;()
                .AddComponentLifeStyle&amp;lt;ICommandExecutor, AsynchronousExecutor&amp;gt;(LifestyleType.Singleton)
                .AddComponentLifeStyle&amp;lt;ICommandExecutor, UnitOfWorkExecutor&amp;gt;(LifestyleType.Singleton)
                .AddComponentLifeStyle&amp;lt;MainForm&amp;gt;(LifestyleType.Transient)
                .AddComponentLifeStyle&amp;lt;IPresenter, Presenter&amp;gt;(LifestyleType.Transient)
                .AddComponentLifeStyle&amp;lt;IService, Service&amp;gt;(LifestyleType.Transient)
                .Register(Component
                              .For&amp;lt;SynchronizationContext&amp;gt;()
                              .LifeStyle.Is(LifestyleType.Singleton)
                              .UsingFactoryMethod&amp;lt;SynchronizationContext&amp;gt;(CreateSynchronizationContext));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(container.Resolve&amp;lt;MainForm&amp;gt;());
        }

        private static SynchronizationContext CreateSynchronizationContext()
        {
            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
            }
            return SynchronizationContext.Current;
        }
    }&lt;/pre&gt;</description></item><item><title>CurrentSessionContext for Desktop development</title><link>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/revision/2.aspx</link><pubDate>Fri, 06 Nov 2009 19:03:37 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:296</guid><dc:creator>Jason Meckley</dc:creator><comments>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/comments.aspx</comments><description>Revision 2 posted to How to by Jason Meckley on 06/11/2009 04:03:37 p.m.&lt;br /&gt;
&lt;h2&gt;CurrentSessionContext for Desktop development&lt;/h2&gt;
&lt;div style="font-size: 90%;"&gt;Filed under: Session, IoC container, CurrentSessionContext&lt;/div&gt;

&lt;p&gt;I have used current session contexts in web applications with the ManagedWebContext class. I wanted to get this working in a non-asp.net environment though. And I wanted to keep the UI responsive, which means pushing as much as possible to the background.&amp;nbsp; I took a queue from Jeremy Miller&amp;#39;s article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee309512.aspx"&gt;functional programming&lt;/a&gt;. To that end, here is one approach to managing Sessions in a threaded environment.&lt;/p&gt;
&lt;p&gt;we will utilize the typical MVP triad injecting our view into the presenter.&lt;/p&gt;
&lt;pre&gt;    public class Presenter : IPresenter
    {
        private readonly IView view;
        private readonly IService service;
        private readonly ICommandExecutor executor;

        public Presenter(IView view, IService service, ICommandExecutor executor)
        {
            this.view = view;
            this.service = service;
            this.executor = executor;
        }

        public virtual void UpdateView()
        {
            executor.Execute(() =&amp;gt;
                                 {
                                     var text = service.GetData(1);
                                     return () =&amp;gt; view.UpdateUserInterface(text);
                                 });
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;So what is the ICommandExecutor? This is where we centralize threading and session management. For SoC I have devided this into 2 implementations. one for threading the other for session management.&lt;/p&gt;
&lt;pre&gt;    public class AsynchronousExecutor : ICommandExecutor
    {
        private readonly SynchronizationContext synchronizationContext;
        private readonly ICommandExecutor executor;

        public AsynchronousExecutor(SynchronizationContext synchronizationContext, ICommandExecutor executor)
        {
            this.synchronizationContext = synchronizationContext;
            this.executor = executor;
        }

        public void Execute(Action action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(action));
        }

        public void Execute(Func&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;action&amp;gt;&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;&amp;lt;Action&amp;gt;&lt;/span&gt; action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(() =&amp;gt;
                                                                     {
                                                                         var continuation = action();
                                                                         synchronizationContext.Send(x =&amp;gt; continuation(), null);
                                                                     }));
        }
    }

    public class UnitOfWorkExecutor : ICommandExecutor
    {
        private readonly ISessionFactory factory;

        public UnitOfWorkExecutor(ISessionFactory factory)
        {
            this.factory = factory;
        }

        public void Execute(Action action)
        {
            ExecuteWithinAUnitOfWork(action);
        }

        public void Execute(Func&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;action&amp;gt;&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;&amp;lt;Action&amp;gt;&lt;/span&gt; action)
        {
            ExecuteWithinAUnitOfWork(() =&amp;gt; action());
        }

        private void ExecuteWithinAUnitOfWork(Action action)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    CurrentSessionContext.Bind(factory.OpenSession());
                    action();
                    transaction.Complete();
                }
            }
            finally
            {
                var session = CurrentSessionContext.Unbind(factory);
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
    }&lt;br /&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;/action&amp;gt;&amp;lt;/action&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;AsynchronousExecutor pushes work to the background while UnitOfWorkExecutor sets up the context of a session. For information on synchronizationContext I will defer you to Jeremy&amp;#39;s MSDN article. 2 steps left. 1) Configure NH and 2) wire this together.&lt;/p&gt;
&lt;p&gt;To configure NH we will use Fluent NHibernate. The important part is setting the CurrentSessionContext property. For those not using programmatic configuration, you would set the property in the hibernate.config file along with the other session factory configs.&lt;/p&gt;
&lt;p&gt;For wiring I&amp;#39;m using Castle Windsor. Any IoC should allow for something similar though. after placing the configuration and factory in the kernel we can use a factory method to resolve the session from the kernel. Note that the lifestyle of session is Transient. this is crucial, otherwise the sessions will not resolve correctly. We will use the same technique for resolving the SynchronizationContext as well.&lt;/p&gt;
&lt;p&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;action&amp;gt;&amp;lt;action&amp;gt;&amp;lt;/action&amp;gt;&amp;lt;/action&amp;gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;    public class NHibernateFacility : AbstractFacility
    {
        protected override void Init()
        {
            var configuration = Fluently
                .Configure()
                .Database(() =&amp;gt; MsSqlConfiguration.MsSql2000)
                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssembly(GetType().Assembly))
                .ExposeConfiguration(ExtendConfiguration)
                .BuildConfiguration();

            Kernel.AddComponentInstance(&amp;quot;configuration&amp;quot;, configuration);
            Kernel.AddComponentInstance(&amp;quot;factory&amp;quot;, configuration.BuildSessionFactory());
            Kernel.Register(Component
                                .For&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;isession&amp;gt;()&lt;/span&gt;
                                &lt;span style="background: SpringGreen;"&gt;&amp;lt;ISession&amp;gt;()&lt;/span&gt;
                                .LifeStyle.Is(LifestyleType.Transient)
                                .UsingFactoryMethod(k =&amp;gt; k.Resolve&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;isessionfactory&amp;gt;().GetCurrentSession()));&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;&amp;lt;ISessionFactory&amp;gt;().GetCurrentSession()));&lt;/span&gt;
        }

        private static void ExtendConfiguration(Configuration cfg)
        {
            cfg.SetProperty(Environment.CurrentSessionContextClass, typeof(ThreadStaticSessionContext).AssemblyQualifiedName);
        }
    }&lt;br /&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;isession&amp;gt;&amp;lt;isessionfactory&amp;gt;Finally,&lt;/span&gt; &lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;&lt;span style="background: SpringGreen;"&gt;Finally&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;,&lt;/span&gt; we wire up the entire container.&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;span style="text-decoration: line-through; color: red;"&gt;&amp;lt;isession&amp;gt;&amp;lt;isessionfactory&amp;gt;&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;    &lt;span style="background: SpringGreen;"&gt;internal&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;static&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;class&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;Program&lt;/span&gt;
    &lt;span style="background: SpringGreen;"&gt;{&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;private&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;static&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;IWindsorContainer&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;container&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;

        &lt;span style="background: SpringGreen;"&gt;[&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;STAThread]&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;private&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;static&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;void&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;Main(&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;)&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;{&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;container&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;=&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;new&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;WindsorContainer(&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddFacility&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;FactorySupportFacility&amp;gt;()&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddFacility&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;NHibernateFacility&amp;gt;()&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddComponentLifeStyle&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;ICommandExecutor,&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;AsynchronousExecutor&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;gt;(LifestyleType.Singleton)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddComponentLifeStyle&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;ICommandExecutor,&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;UnitOfWorkExecutor&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;gt;(LifestyleType.Singleton)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddComponentLifeStyle&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;MainForm&amp;gt;(LifestyleType.Transient)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddComponentLifeStyle&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;IPresenter,&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;Presenter&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;gt;(LifestyleType.Transient)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;AddComponentLifeStyle&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;IService,&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;Service&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;gt;(LifestyleType.Transient)&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;Register(Component&lt;/span&gt;
                              &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;For&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;SynchronizationContext&amp;gt;()&lt;/span&gt;
                              &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;LifeStyle.Is(LifestyleType.Singleton)&lt;/span&gt;
                              &lt;span style="background: SpringGreen;"&gt;.&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;UsingFactoryMethod&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;SynchronizationContext&amp;gt;(CreateSynchronizationContext));&lt;/span&gt;

            &lt;span style="background: SpringGreen;"&gt;Application.EnableVisualStyles()&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;Application.SetCompatibleTextRenderingDefault(false)&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;Application.Run(container.Resolve&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;&amp;lt;MainForm&amp;gt;());&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;}&lt;/span&gt;

        &lt;span style="background: SpringGreen;"&gt;private&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;static&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;SynchronizationContext&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;CreateSynchronizationContext(&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;)&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;{&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;if&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;(&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;SynchronizationContext.Current&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;=&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;=&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;null&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;)&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;{&lt;/span&gt;
                &lt;span style="background: SpringGreen;"&gt;SynchronizationContext.SetSynchronizationContext(new&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;WindowsFormsSynchronizationContext())&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;}&lt;/span&gt;
            &lt;span style="background: SpringGreen;"&gt;return&lt;/span&gt; &lt;span style="background: SpringGreen;"&gt;SynchronizationContext.Current&lt;/span&gt;&lt;span style="background: SpringGreen;"&gt;;&lt;/span&gt;
        &lt;span style="background: SpringGreen;"&gt;}&lt;/span&gt;
    &lt;span style="background: SpringGreen;"&gt;}&lt;/span&gt;&lt;/pre&gt;</description></item><item><title>CurrentSessionContext for Desktop development</title><link>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/revision/1.aspx</link><pubDate>Fri, 06 Nov 2009 18:56:45 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:295</guid><dc:creator>Jason Meckley</dc:creator><comments>http://nhforge.org/wikis/howtonh/currentsessioncontext-for-desktop-development/comments.aspx</comments><description>Revision 1 posted to How to by Jason Meckley on 06/11/2009 03:56:45 p.m.&lt;br /&gt;
&lt;p&gt;I have used current session contexts in web applications with the ManagedWebContext class. I wanted to get this working in a non-asp.net environment though. And I wanted to keep the UI responsive, which means pushing as much as possible to the background.&amp;nbsp; I took a queue from Jeremy Miller&amp;#39;s article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee309512.aspx"&gt;functional programming&lt;/a&gt;. To that end, here is one approach to managing Sessions in a threaded environment.&lt;/p&gt;
&lt;p&gt;we will utilize the typical MVP triad injecting our view into the presenter.&lt;/p&gt;
&lt;pre&gt;    public class Presenter : IPresenter
    {
        private readonly IView view;
        private readonly IService service;
        private readonly ICommandExecutor executor;

        public Presenter(IView view, IService service, ICommandExecutor executor)
        {
            this.view = view;
            this.service = service;
            this.executor = executor;
        }

        public virtual void UpdateView()
        {
            executor.Execute(() =&amp;gt;
                                 {
                                     var text = service.GetData(1);
                                     return () =&amp;gt; view.UpdateUserInterface(text);
                                 });
        }
    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;So what is the ICommandExecutor? This is where we centralize threading and session management. For SoC I have devided this into 2 implementations. one for threading the other for session management.&lt;/p&gt;
&lt;pre&gt;    public class AsynchronousExecutor : ICommandExecutor
    {
        private readonly SynchronizationContext synchronizationContext;
        private readonly ICommandExecutor executor;

        public AsynchronousExecutor(SynchronizationContext synchronizationContext, ICommandExecutor executor)
        {
            this.synchronizationContext = synchronizationContext;
            this.executor = executor;
        }

        public void Execute(Action action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(action));
        }

        public void Execute(Func&amp;lt;action&amp;gt; action)
        {
            ThreadPool.QueueUserWorkItem(item =&amp;gt; executor.Execute(() =&amp;gt;
                                                                     {
                                                                         var continuation = action();
                                                                         synchronizationContext.Send(x =&amp;gt; continuation(), null);
                                                                     }));
        }
    }

    public class UnitOfWorkExecutor : ICommandExecutor
    {
        private readonly ISessionFactory factory;

        public UnitOfWorkExecutor(ISessionFactory factory)
        {
            this.factory = factory;
        }

        public void Execute(Action action)
        {
            ExecuteWithinAUnitOfWork(action);
        }

        public void Execute(Func&amp;lt;action&amp;gt; action)
        {
            ExecuteWithinAUnitOfWork(() =&amp;gt; action());
        }

        private void ExecuteWithinAUnitOfWork(Action action)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    CurrentSessionContext.Bind(factory.OpenSession());
                    action();
                    transaction.Complete();
                }
            }
            finally
            {
                var session = CurrentSessionContext.Unbind(factory);
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
    }&lt;br /&gt;&amp;lt;/action&amp;gt;&amp;lt;/action&amp;gt;&lt;/pre&gt;
&lt;p&gt;AsynchronousExecutor pushes work to the background while UnitOfWorkExecutor sets up the context of a session. For information on synchronizationContext I will defer you to Jeremy&amp;#39;s MSDN article. 2 steps left. 1) Configure NH and 2) wire this together.&lt;/p&gt;
&lt;p&gt;To configure NH we will use Fluent NHibernate. The important part is setting the CurrentSessionContext property. For those not using programmatic configuration, you would set the property in the hibernate.config file along with the other session factory configs.&lt;/p&gt;
&lt;p&gt;For wiring I&amp;#39;m using Castle Windsor. Any IoC should allow for something similar though. after placing the configuration and factory in the kernel we can use a factory method to resolve the session from the kernel. Note that the lifestyle of session is Transient. this is crucial, otherwise the sessions will not resolve correctly. We will use the same technique for resolving the SynchronizationContext as well.&lt;/p&gt;
&lt;p&gt;&amp;lt;action&amp;gt;&amp;lt;action&amp;gt;&amp;lt;/action&amp;gt;&amp;lt;/action&amp;gt;&lt;/p&gt;
&lt;pre&gt;    public class NHibernateFacility : AbstractFacility
    {
        protected override void Init()
        {
            var configuration = Fluently
                .Configure()
                .Database(() =&amp;gt; MsSqlConfiguration.MsSql2000)
                .Mappings(m =&amp;gt; m.FluentMappings.AddFromAssembly(GetType().Assembly))
                .ExposeConfiguration(ExtendConfiguration)
                .BuildConfiguration();

            Kernel.AddComponentInstance(&amp;quot;configuration&amp;quot;, configuration);
            Kernel.AddComponentInstance(&amp;quot;factory&amp;quot;, configuration.BuildSessionFactory());
            Kernel.Register(Component
                                .For&amp;lt;isession&amp;gt;()
                                .LifeStyle.Is(LifestyleType.Transient)
                                .UsingFactoryMethod(k =&amp;gt; k.Resolve&amp;lt;isessionfactory&amp;gt;().GetCurrentSession()));
        }

        private static void ExtendConfiguration(Configuration cfg)
        {
            cfg.SetProperty(Environment.CurrentSessionContextClass, typeof(ThreadStaticSessionContext).AssemblyQualifiedName);
        }
    }&lt;br /&gt;&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;isession&amp;gt;&amp;lt;isessionfactory&amp;gt;Finally, we wire up the entire container.&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;lt;isession&amp;gt;&amp;lt;isessionfactory&amp;gt;&amp;lt;/isessionfactory&amp;gt;&amp;lt;/isession&amp;gt;&lt;/p&gt;</description></item></channel></rss>
