<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Elegant Code &#187; WCF</title>
	<atom:link href="http://elegantcode.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrating Castle Windsor and NHibernate with WCF</title>
		<link>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integrating-castle-windsor-and-nhibernate-with-wcf</link>
		<comments>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/#comments</comments>
		<pubDate>Sun, 18 May 2008 14:08:20 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/</guid>
		<description><![CDATA[Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. Yesterday I did a small spike to figure out how this should work. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now, we were using the <a href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html" target="_blank">NHibernate facility</a> of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. </p>  <p>Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used <a href="http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html" target="_blank">this excellent blog</a> post written by <a href="http://orand.blogspot.com/" target="_blank">Oran Dennison</a> as my guide. </p>  <p>First I created a class that implemented the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehavior</a> interface.</p>  <p>   <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8f86f82a-a0be-44ef-94b2-05d30085febc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceBehavior : IServiceBehavior
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceBehavior()
    {
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> Configuration()
            .Configure()
            .BuildSessionFactory();

        XmlConfigurator.Configure();    </span><span style="color: #008000; ">//</span><span style="color: #008000; "> Log4Net</span><span style="color: #008000; ">
</span><span style="color: #000000; ">    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ApplyDispatchBehavior(
             ServiceDescription serviceDescription, 
             ServiceHostBase serviceHostBase)
    {
        </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(ChannelDispatcherBase cdb </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> 
                serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd </span><span style="color: #000000; ">=</span><span style="color: #000000; "> cdb </span><span style="color: #0000FF; ">as</span><span style="color: #000000; "> ChannelDispatcher;
            </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(cd </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">)
            {
                </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(EndpointDispatcher ed </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider </span><span style="color: #000000; ">=</span><span style="color: #000000; ">
                        </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIInstanceProvider
                            (serviceDescription.ServiceType,
                              _sessionFactory);
                }
            }
        }
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> AddBindingParameters(
                ServiceDescription serviceDescription, 
                ServiceHostBase serviceHostBase,
                Collection</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">ServiceEndpoint</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; "> endpoints, 
                BindingParameterCollection bindingParameters) 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> Validate(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase) 
    { }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html" target="_blank">SessionFactory</a> is created in the constructor because the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior.aspx" target="_blank">ApplyDispatchBehaviour</a> method can be called multiple times (for each endpoint). </p>

<p>The next step is to create an instance provider by creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:d1255b8d-431d-469d-a9e7-f45063afb49b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIInstanceProvider : IInstanceProvider
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">const</span><span style="color: #000000; "> String NHibernateSessionKey </span><span style="color: #000000; ">=</span><span style="color: #000000; "> 
        </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">NHibernate.Session</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">;

    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> Type _serviceType;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> IDependencyContainer _dependencyContainer;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIInstanceProvider(Type serviceType,
                               ISessionFactory sessionFactory)
    {
        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> serviceType, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null != serviceType</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _serviceType </span><span style="color: #000000; ">=</span><span style="color: #000000; "> serviceType;

        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> sessionFactory, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null = sessionFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> sessionFactory;
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> GetInstance(instanceContext, </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext, 
                                Message message)
    {
        _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DependencyContainer();

        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> _sessionFactory.OpenSession();
        _dependencyContainer
          .AddComponentInstance(NHibernateSessionKey, _session);

        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _dependencyContainer.Resolve(_serviceType);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ReleaseInstance(InstanceContext instanceContext, 
                                 Object instance)
    {
        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _session)
        {
            _session.Close();
            _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }

        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _dependencyContainer)
        {
            _dependencyContainer.Dispose();
            _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>I created a wrapper class around for Castle Windsor named <em>DependencyContainer</em>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms587089.aspx" target="_blank">GetInstance</a> method opens a new session using the <em>SessionFactory</em> object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6daed72f-d1d2-4d83-bad4-520fb4849c4e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> SomeAggregateRepository
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregateRepository(ISession session)
    {
        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> session;
    }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregate Get(Int64 id) 
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _session.Get</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">SomeAggregate</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; ">(id);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>When our service operation has been executed, the NHibernate is released by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance.aspx" target="_blank">ReleaseInstance</a> method. Finishing our example, we need to implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHost</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHostFactory</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:82ea4d3b-0b5c-4b43-8d05-7042d606650b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHost : ServiceHost
{
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DependencyInjectionServiceHost() 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">() 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceHost(Type serviceType, 
                         </span><span style="color: #0000FF; ">params</span><span style="color: #000000; "> Uri[] baseAddresses) 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">(serviceType, baseAddresses) 
    { }

    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> OnOpening()
    {
        Description.Behaviors.Add(</span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceBehavior());
        </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">.OnOpening();
    }
}

</span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHostFactory : ServiceHostFactory
{
    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> ServiceHost CreateServiceHost(
            Type serviceType, Uri[] baseAddresses)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceHost(serviceType, baseAddresses);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The custom ServiceHostFactory class can now be used in the ServiceHost file required when doing IIS hosting:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:96b67456-7704-422c-b22f-8dda187e6729" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000; ">&lt;%</span><span style="color: #000000; ">@ ServiceHost Language</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">C#</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Debug</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">true</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Service</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.MyWindsorService</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Factory</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.DIServiceHostFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">
                CodeBehind</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">MyWindsorService.svc.cs</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> </span><span style="color: #000000; ">%&gt;</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>There is also another way for achieving this that I will be investigating the next week or so using the <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" target="_blank">WCF Integration Facility</a> for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk. </p>

<p>If you have any thoughts, improvements or suggestions I'm glad to hear them from you, my dear reader. It's the only way I'll ever learn :-). </p>

<p>Till next time.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>WCF friction</title>
		<link>http://elegantcode.com/2008/05/13/wcf-friction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-friction</link>
		<comments>http://elegantcode.com/2008/05/13/wcf-friction/#comments</comments>
		<pubDate>Tue, 13 May 2008 18:10:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/13/wcf-friction/</guid>
		<description><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception: System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly. This is really helpful, isn't it? Fortunately there is some [...]]]></description>
			<content:encoded><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception:

<em>System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly.</em>

This is really helpful, isn't it? Fortunately there is some tool that helped me out a great deal: <a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" target="_blank">Service Trace Viewer Tool (SvcTraceViewer.exe)</a>. Turns out that I forgot to place a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> attribute on one of my DTO objects.

Why am I too stupid to deduce this from the exception message in the first place?]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/13/wcf-friction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Demonstrating WCF: Beyond the endpoints</title>
	<atom:link href="http://elegantcode.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Elegant Code &#187; WCF</title>
	<atom:link href="http://elegantcode.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrating Castle Windsor and NHibernate with WCF</title>
		<link>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integrating-castle-windsor-and-nhibernate-with-wcf</link>
		<comments>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/#comments</comments>
		<pubDate>Sun, 18 May 2008 14:08:20 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/</guid>
		<description><![CDATA[Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. Yesterday I did a small spike to figure out how this should work. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now, we were using the <a href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html" target="_blank">NHibernate facility</a> of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. </p>  <p>Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used <a href="http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html" target="_blank">this excellent blog</a> post written by <a href="http://orand.blogspot.com/" target="_blank">Oran Dennison</a> as my guide. </p>  <p>First I created a class that implemented the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehavior</a> interface.</p>  <p>   <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8f86f82a-a0be-44ef-94b2-05d30085febc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceBehavior : IServiceBehavior
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceBehavior()
    {
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> Configuration()
            .Configure()
            .BuildSessionFactory();

        XmlConfigurator.Configure();    </span><span style="color: #008000; ">//</span><span style="color: #008000; "> Log4Net</span><span style="color: #008000; ">
</span><span style="color: #000000; ">    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ApplyDispatchBehavior(
             ServiceDescription serviceDescription, 
             ServiceHostBase serviceHostBase)
    {
        </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(ChannelDispatcherBase cdb </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> 
                serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd </span><span style="color: #000000; ">=</span><span style="color: #000000; "> cdb </span><span style="color: #0000FF; ">as</span><span style="color: #000000; "> ChannelDispatcher;
            </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(cd </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">)
            {
                </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(EndpointDispatcher ed </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider </span><span style="color: #000000; ">=</span><span style="color: #000000; ">
                        </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIInstanceProvider
                            (serviceDescription.ServiceType,
                              _sessionFactory);
                }
            }
        }
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> AddBindingParameters(
                ServiceDescription serviceDescription, 
                ServiceHostBase serviceHostBase,
                Collection</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">ServiceEndpoint</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; "> endpoints, 
                BindingParameterCollection bindingParameters) 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> Validate(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase) 
    { }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html" target="_blank">SessionFactory</a> is created in the constructor because the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior.aspx" target="_blank">ApplyDispatchBehaviour</a> method can be called multiple times (for each endpoint). </p>

<p>The next step is to create an instance provider by creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:d1255b8d-431d-469d-a9e7-f45063afb49b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIInstanceProvider : IInstanceProvider
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">const</span><span style="color: #000000; "> String NHibernateSessionKey </span><span style="color: #000000; ">=</span><span style="color: #000000; "> 
        </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">NHibernate.Session</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">;

    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> Type _serviceType;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> IDependencyContainer _dependencyContainer;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIInstanceProvider(Type serviceType,
                               ISessionFactory sessionFactory)
    {
        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> serviceType, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null != serviceType</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _serviceType </span><span style="color: #000000; ">=</span><span style="color: #000000; "> serviceType;

        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> sessionFactory, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null = sessionFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> sessionFactory;
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> GetInstance(instanceContext, </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext, 
                                Message message)
    {
        _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DependencyContainer();

        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> _sessionFactory.OpenSession();
        _dependencyContainer
          .AddComponentInstance(NHibernateSessionKey, _session);

        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _dependencyContainer.Resolve(_serviceType);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ReleaseInstance(InstanceContext instanceContext, 
                                 Object instance)
    {
        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _session)
        {
            _session.Close();
            _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }

        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _dependencyContainer)
        {
            _dependencyContainer.Dispose();
            _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>I created a wrapper class around for Castle Windsor named <em>DependencyContainer</em>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms587089.aspx" target="_blank">GetInstance</a> method opens a new session using the <em>SessionFactory</em> object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6daed72f-d1d2-4d83-bad4-520fb4849c4e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> SomeAggregateRepository
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregateRepository(ISession session)
    {
        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> session;
    }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregate Get(Int64 id) 
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _session.Get</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">SomeAggregate</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; ">(id);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>When our service operation has been executed, the NHibernate is released by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance.aspx" target="_blank">ReleaseInstance</a> method. Finishing our example, we need to implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHost</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHostFactory</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:82ea4d3b-0b5c-4b43-8d05-7042d606650b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHost : ServiceHost
{
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DependencyInjectionServiceHost() 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">() 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceHost(Type serviceType, 
                         </span><span style="color: #0000FF; ">params</span><span style="color: #000000; "> Uri[] baseAddresses) 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">(serviceType, baseAddresses) 
    { }

    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> OnOpening()
    {
        Description.Behaviors.Add(</span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceBehavior());
        </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">.OnOpening();
    }
}

</span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHostFactory : ServiceHostFactory
{
    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> ServiceHost CreateServiceHost(
            Type serviceType, Uri[] baseAddresses)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceHost(serviceType, baseAddresses);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The custom ServiceHostFactory class can now be used in the ServiceHost file required when doing IIS hosting:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:96b67456-7704-422c-b22f-8dda187e6729" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000; ">&lt;%</span><span style="color: #000000; ">@ ServiceHost Language</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">C#</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Debug</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">true</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Service</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.MyWindsorService</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Factory</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.DIServiceHostFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">
                CodeBehind</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">MyWindsorService.svc.cs</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> </span><span style="color: #000000; ">%&gt;</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>There is also another way for achieving this that I will be investigating the next week or so using the <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" target="_blank">WCF Integration Facility</a> for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk. </p>

<p>If you have any thoughts, improvements or suggestions I'm glad to hear them from you, my dear reader. It's the only way I'll ever learn :-). </p>

<p>Till next time.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>WCF friction</title>
		<link>http://elegantcode.com/2008/05/13/wcf-friction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-friction</link>
		<comments>http://elegantcode.com/2008/05/13/wcf-friction/#comments</comments>
		<pubDate>Tue, 13 May 2008 18:10:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/13/wcf-friction/</guid>
		<description><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception: System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly. This is really helpful, isn't it? Fortunately there is some [...]]]></description>
			<content:encoded><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception:

<em>System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly.</em>

This is really helpful, isn't it? Fortunately there is some tool that helped me out a great deal: <a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" target="_blank">Service Trace Viewer Tool (SvcTraceViewer.exe)</a>. Turns out that I forgot to place a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> attribute on one of my DTO objects.

Why am I too stupid to deduce this from the exception message in the first place?]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/13/wcf-friction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Demonstrating WCF: Beyond the endpoints</title>
		<link>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integrating-castle-windsor-and-nhibernate-with-wcf</link>
		<comments>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/#comments</comments>
		<pubDate>Sun, 18 May 2008 14:08:20 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/</guid>
		<description><![CDATA[Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. Yesterday I did a small spike to figure out how this should work. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now, we were using the <a href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html" target="_blank">NHibernate facility</a> of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. </p>  <p>Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used <a href="http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html" target="_blank">this excellent blog</a> post written by <a href="http://orand.blogspot.com/" target="_blank">Oran Dennison</a> as my guide. </p>  <p>First I created a class that implemented the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehavior</a> interface.</p>  <p>   <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8f86f82a-a0be-44ef-94b2-05d30085febc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceBehavior : IServiceBehavior
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceBehavior()
    {
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> Configuration()
            .Configure()
            .BuildSessionFactory();

        XmlConfigurator.Configure();    </span><span style="color: #008000; ">//</span><span style="color: #008000; "> Log4Net</span><span style="color: #008000; ">
</span><span style="color: #000000; ">    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ApplyDispatchBehavior(
             ServiceDescription serviceDescription, 
             ServiceHostBase serviceHostBase)
    {
        </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(ChannelDispatcherBase cdb </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> 
                serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd </span><span style="color: #000000; ">=</span><span style="color: #000000; "> cdb </span><span style="color: #0000FF; ">as</span><span style="color: #000000; "> ChannelDispatcher;
            </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(cd </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">)
            {
                </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(EndpointDispatcher ed </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider </span><span style="color: #000000; ">=</span><span style="color: #000000; ">
                        </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIInstanceProvider
                            (serviceDescription.ServiceType,
                              _sessionFactory);
                }
            }
        }
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> AddBindingParameters(
                ServiceDescription serviceDescription, 
                ServiceHostBase serviceHostBase,
                Collection</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">ServiceEndpoint</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; "> endpoints, 
                BindingParameterCollection bindingParameters) 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> Validate(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase) 
    { }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html" target="_blank">SessionFactory</a> is created in the constructor because the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior.aspx" target="_blank">ApplyDispatchBehaviour</a> method can be called multiple times (for each endpoint). </p>

<p>The next step is to create an instance provider by creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:d1255b8d-431d-469d-a9e7-f45063afb49b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIInstanceProvider : IInstanceProvider
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">const</span><span style="color: #000000; "> String NHibernateSessionKey </span><span style="color: #000000; ">=</span><span style="color: #000000; "> 
        </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">NHibernate.Session</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">;

    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> Type _serviceType;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> IDependencyContainer _dependencyContainer;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIInstanceProvider(Type serviceType,
                               ISessionFactory sessionFactory)
    {
        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> serviceType, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null != serviceType</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _serviceType </span><span style="color: #000000; ">=</span><span style="color: #000000; "> serviceType;

        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> sessionFactory, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null = sessionFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> sessionFactory;
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> GetInstance(instanceContext, </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext, 
                                Message message)
    {
        _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DependencyContainer();

        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> _sessionFactory.OpenSession();
        _dependencyContainer
          .AddComponentInstance(NHibernateSessionKey, _session);

        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _dependencyContainer.Resolve(_serviceType);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ReleaseInstance(InstanceContext instanceContext, 
                                 Object instance)
    {
        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _session)
        {
            _session.Close();
            _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }

        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _dependencyContainer)
        {
            _dependencyContainer.Dispose();
            _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>I created a wrapper class around for Castle Windsor named <em>DependencyContainer</em>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms587089.aspx" target="_blank">GetInstance</a> method opens a new session using the <em>SessionFactory</em> object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6daed72f-d1d2-4d83-bad4-520fb4849c4e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> SomeAggregateRepository
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregateRepository(ISession session)
    {
        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> session;
    }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregate Get(Int64 id) 
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _session.Get</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">SomeAggregate</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; ">(id);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>When our service operation has been executed, the NHibernate is released by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance.aspx" target="_blank">ReleaseInstance</a> method. Finishing our example, we need to implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHost</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHostFactory</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:82ea4d3b-0b5c-4b43-8d05-7042d606650b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHost : ServiceHost
{
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DependencyInjectionServiceHost() 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">() 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceHost(Type serviceType, 
                         </span><span style="color: #0000FF; ">params</span><span style="color: #000000; "> Uri[] baseAddresses) 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">(serviceType, baseAddresses) 
    { }

    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> OnOpening()
    {
        Description.Behaviors.Add(</span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceBehavior());
        </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">.OnOpening();
    }
}

</span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHostFactory : ServiceHostFactory
{
    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> ServiceHost CreateServiceHost(
            Type serviceType, Uri[] baseAddresses)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceHost(serviceType, baseAddresses);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The custom ServiceHostFactory class can now be used in the ServiceHost file required when doing IIS hosting:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:96b67456-7704-422c-b22f-8dda187e6729" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000; ">&lt;%</span><span style="color: #000000; ">@ ServiceHost Language</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">C#</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Debug</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">true</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Service</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.MyWindsorService</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Factory</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.DIServiceHostFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">
                CodeBehind</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">MyWindsorService.svc.cs</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> </span><span style="color: #000000; ">%&gt;</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>There is also another way for achieving this that I will be investigating the next week or so using the <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" target="_blank">WCF Integration Facility</a> for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk. </p>

<p>If you have any thoughts, improvements or suggestions I'm glad to hear them from you, my dear reader. It's the only way I'll ever learn :-). </p>

<p>Till next time.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; WCF</title>
	<atom:link href="http://elegantcode.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrating Castle Windsor and NHibernate with WCF</title>
		<link>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integrating-castle-windsor-and-nhibernate-with-wcf</link>
		<comments>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/#comments</comments>
		<pubDate>Sun, 18 May 2008 14:08:20 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/</guid>
		<description><![CDATA[Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. Yesterday I did a small spike to figure out how this should work. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now, we were using the <a href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html" target="_blank">NHibernate facility</a> of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. </p>  <p>Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used <a href="http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html" target="_blank">this excellent blog</a> post written by <a href="http://orand.blogspot.com/" target="_blank">Oran Dennison</a> as my guide. </p>  <p>First I created a class that implemented the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehavior</a> interface.</p>  <p>   <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8f86f82a-a0be-44ef-94b2-05d30085febc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceBehavior : IServiceBehavior
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceBehavior()
    {
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> Configuration()
            .Configure()
            .BuildSessionFactory();

        XmlConfigurator.Configure();    </span><span style="color: #008000; ">//</span><span style="color: #008000; "> Log4Net</span><span style="color: #008000; ">
</span><span style="color: #000000; ">    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ApplyDispatchBehavior(
             ServiceDescription serviceDescription, 
             ServiceHostBase serviceHostBase)
    {
        </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(ChannelDispatcherBase cdb </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> 
                serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd </span><span style="color: #000000; ">=</span><span style="color: #000000; "> cdb </span><span style="color: #0000FF; ">as</span><span style="color: #000000; "> ChannelDispatcher;
            </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(cd </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">)
            {
                </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(EndpointDispatcher ed </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider </span><span style="color: #000000; ">=</span><span style="color: #000000; ">
                        </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIInstanceProvider
                            (serviceDescription.ServiceType,
                              _sessionFactory);
                }
            }
        }
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> AddBindingParameters(
                ServiceDescription serviceDescription, 
                ServiceHostBase serviceHostBase,
                Collection</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">ServiceEndpoint</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; "> endpoints, 
                BindingParameterCollection bindingParameters) 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> Validate(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase) 
    { }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html" target="_blank">SessionFactory</a> is created in the constructor because the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior.aspx" target="_blank">ApplyDispatchBehaviour</a> method can be called multiple times (for each endpoint). </p>

<p>The next step is to create an instance provider by creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:d1255b8d-431d-469d-a9e7-f45063afb49b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIInstanceProvider : IInstanceProvider
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">const</span><span style="color: #000000; "> String NHibernateSessionKey </span><span style="color: #000000; ">=</span><span style="color: #000000; "> 
        </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">NHibernate.Session</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">;

    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> Type _serviceType;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> IDependencyContainer _dependencyContainer;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIInstanceProvider(Type serviceType,
                               ISessionFactory sessionFactory)
    {
        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> serviceType, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null != serviceType</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _serviceType </span><span style="color: #000000; ">=</span><span style="color: #000000; "> serviceType;

        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> sessionFactory, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null = sessionFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> sessionFactory;
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> GetInstance(instanceContext, </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext, 
                                Message message)
    {
        _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DependencyContainer();

        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> _sessionFactory.OpenSession();
        _dependencyContainer
          .AddComponentInstance(NHibernateSessionKey, _session);

        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _dependencyContainer.Resolve(_serviceType);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ReleaseInstance(InstanceContext instanceContext, 
                                 Object instance)
    {
        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _session)
        {
            _session.Close();
            _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }

        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _dependencyContainer)
        {
            _dependencyContainer.Dispose();
            _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>I created a wrapper class around for Castle Windsor named <em>DependencyContainer</em>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms587089.aspx" target="_blank">GetInstance</a> method opens a new session using the <em>SessionFactory</em> object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6daed72f-d1d2-4d83-bad4-520fb4849c4e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> SomeAggregateRepository
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregateRepository(ISession session)
    {
        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> session;
    }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregate Get(Int64 id) 
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _session.Get</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">SomeAggregate</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; ">(id);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>When our service operation has been executed, the NHibernate is released by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance.aspx" target="_blank">ReleaseInstance</a> method. Finishing our example, we need to implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHost</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHostFactory</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:82ea4d3b-0b5c-4b43-8d05-7042d606650b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHost : ServiceHost
{
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DependencyInjectionServiceHost() 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">() 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceHost(Type serviceType, 
                         </span><span style="color: #0000FF; ">params</span><span style="color: #000000; "> Uri[] baseAddresses) 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">(serviceType, baseAddresses) 
    { }

    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> OnOpening()
    {
        Description.Behaviors.Add(</span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceBehavior());
        </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">.OnOpening();
    }
}

</span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHostFactory : ServiceHostFactory
{
    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> ServiceHost CreateServiceHost(
            Type serviceType, Uri[] baseAddresses)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceHost(serviceType, baseAddresses);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The custom ServiceHostFactory class can now be used in the ServiceHost file required when doing IIS hosting:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:96b67456-7704-422c-b22f-8dda187e6729" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000; ">&lt;%</span><span style="color: #000000; ">@ ServiceHost Language</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">C#</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Debug</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">true</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Service</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.MyWindsorService</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Factory</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.DIServiceHostFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">
                CodeBehind</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">MyWindsorService.svc.cs</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> </span><span style="color: #000000; ">%&gt;</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>There is also another way for achieving this that I will be investigating the next week or so using the <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" target="_blank">WCF Integration Facility</a> for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk. </p>

<p>If you have any thoughts, improvements or suggestions I'm glad to hear them from you, my dear reader. It's the only way I'll ever learn :-). </p>

<p>Till next time.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>WCF friction</title>
		<link>http://elegantcode.com/2008/05/13/wcf-friction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-friction</link>
		<comments>http://elegantcode.com/2008/05/13/wcf-friction/#comments</comments>
		<pubDate>Tue, 13 May 2008 18:10:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/13/wcf-friction/</guid>
		<description><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception: System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly. This is really helpful, isn't it? Fortunately there is some [...]]]></description>
			<content:encoded><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception:

<em>System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly.</em>

This is really helpful, isn't it? Fortunately there is some tool that helped me out a great deal: <a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" target="_blank">Service Trace Viewer Tool (SvcTraceViewer.exe)</a>. Turns out that I forgot to place a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> attribute on one of my DTO objects.

Why am I too stupid to deduce this from the exception message in the first place?]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/13/wcf-friction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Demonstrating WCF: Beyond the endpoints</title>
		<link>http://elegantcode.com/2008/05/13/wcf-friction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-friction</link>
		<comments>http://elegantcode.com/2008/05/13/wcf-friction/#comments</comments>
		<pubDate>Tue, 13 May 2008 18:10:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/13/wcf-friction/</guid>
		<description><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception: System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly. This is really helpful, isn't it? Fortunately there is some [...]]]></description>
			<content:encoded><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception:

<em>System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly.</em>

This is really helpful, isn't it? Fortunately there is some tool that helped me out a great deal: <a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" target="_blank">Service Trace Viewer Tool (SvcTraceViewer.exe)</a>. Turns out that I forgot to place a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> attribute on one of my DTO objects.

Why am I too stupid to deduce this from the exception message in the first place?]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/13/wcf-friction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; WCF</title>
	<atom:link href="http://elegantcode.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrating Castle Windsor and NHibernate with WCF</title>
		<link>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integrating-castle-windsor-and-nhibernate-with-wcf</link>
		<comments>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/#comments</comments>
		<pubDate>Sun, 18 May 2008 14:08:20 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/</guid>
		<description><![CDATA[Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. Yesterday I did a small spike to figure out how this should work. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>Up until now, we were using the <a href="http://www.castleproject.org/container/facilities/trunk/nhibernate/index.html" target="_blank">NHibernate facility</a> of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application. </p>  <p>Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used <a href="http://orand.blogspot.com/2006/10/wcf-service-dependency-injection.html" target="_blank">this excellent blog</a> post written by <a href="http://orand.blogspot.com/" target="_blank">Oran Dennison</a> as my guide. </p>  <p>First I created a class that implemented the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" target="_blank">IServiceBehavior</a> interface.</p>  <p>   <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:8f86f82a-a0be-44ef-94b2-05d30085febc" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceBehavior : IServiceBehavior
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceBehavior()
    {
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> Configuration()
            .Configure()
            .BuildSessionFactory();

        XmlConfigurator.Configure();    </span><span style="color: #008000; ">//</span><span style="color: #008000; "> Log4Net</span><span style="color: #008000; ">
</span><span style="color: #000000; ">    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ApplyDispatchBehavior(
             ServiceDescription serviceDescription, 
             ServiceHostBase serviceHostBase)
    {
        </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(ChannelDispatcherBase cdb </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> 
                serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher cd </span><span style="color: #000000; ">=</span><span style="color: #000000; "> cdb </span><span style="color: #0000FF; ">as</span><span style="color: #000000; "> ChannelDispatcher;
            </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(cd </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">)
            {
                </span><span style="color: #0000FF; ">foreach</span><span style="color: #000000; ">(EndpointDispatcher ed </span><span style="color: #0000FF; ">in</span><span style="color: #000000; "> cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider </span><span style="color: #000000; ">=</span><span style="color: #000000; ">
                        </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIInstanceProvider
                            (serviceDescription.ServiceType,
                              _sessionFactory);
                }
            }
        }
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> AddBindingParameters(
                ServiceDescription serviceDescription, 
                ServiceHostBase serviceHostBase,
                Collection</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">ServiceEndpoint</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; "> endpoints, 
                BindingParameterCollection bindingParameters) 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> Validate(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase) 
    { }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html" target="_blank">SessionFactory</a> is created in the constructor because the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior.aspx" target="_blank">ApplyDispatchBehaviour</a> method can be called multiple times (for each endpoint). </p>

<p>The next step is to create an instance provider by creating a class that implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx" target="_blank">IInstanceProvider</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:d1255b8d-431d-469d-a9e7-f45063afb49b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIInstanceProvider : IInstanceProvider
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">const</span><span style="color: #000000; "> String NHibernateSessionKey </span><span style="color: #000000; ">=</span><span style="color: #000000; "> 
        </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">NHibernate.Session</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">;

    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> Type _serviceType;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> IDependencyContainer _dependencyContainer;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">readonly</span><span style="color: #000000; "> ISessionFactory _sessionFactory;
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIInstanceProvider(Type serviceType,
                               ISessionFactory sessionFactory)
    {
        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> serviceType, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null != serviceType</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _serviceType </span><span style="color: #000000; ">=</span><span style="color: #000000; "> serviceType;

        Debug.Assert(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> sessionFactory, 
                     </span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">null = sessionFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">);
        _sessionFactory </span><span style="color: #000000; ">=</span><span style="color: #000000; "> sessionFactory;
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> GetInstance(instanceContext, </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> Object GetInstance(InstanceContext instanceContext, 
                                Message message)
    {
        _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DependencyContainer();

        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> _sessionFactory.OpenSession();
        _dependencyContainer
          .AddComponentInstance(NHibernateSessionKey, _session);

        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _dependencyContainer.Resolve(_serviceType);
    }

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> ReleaseInstance(InstanceContext instanceContext, 
                                 Object instance)
    {
        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _session)
        {
            _session.Close();
            _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }

        </span><span style="color: #0000FF; ">if</span><span style="color: #000000; ">(</span><span style="color: #0000FF; ">null</span><span style="color: #000000; "> </span><span style="color: #000000; ">!=</span><span style="color: #000000; "> _dependencyContainer)
        {
            _dependencyContainer.Dispose();
            _dependencyContainer </span><span style="color: #000000; ">=</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">null</span><span style="color: #000000; ">;
        }
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>I created a wrapper class around for Castle Windsor named <em>DependencyContainer</em>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms587089.aspx" target="_blank">GetInstance</a> method opens a new session using the <em>SessionFactory</em> object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:6daed72f-d1d2-4d83-bad4-520fb4849c4e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> SomeAggregateRepository
{
    </span><span style="color: #0000FF; ">private</span><span style="color: #000000; "> ISession _session;

    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregateRepository(ISession session)
    {
        _session </span><span style="color: #000000; ">=</span><span style="color: #000000; "> session;
    }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> SomeAggregate Get(Int64 id) 
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> _session.Get</span><span style="color: #000000; ">&lt;</span><span style="color: #000000; ">SomeAggregate</span><span style="color: #000000; ">&gt;</span><span style="color: #000000; ">(id);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>When our service operation has been executed, the NHibernate is released by the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance.aspx" target="_blank">ReleaseInstance</a> method. Finishing our example, we need to implement a custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHost</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" target="_blank">ServiceHostFactory</a>:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:82ea4d3b-0b5c-4b43-8d05-7042d606650b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHost : ServiceHost
{
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DependencyInjectionServiceHost() 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">() 
    { }
    
    </span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> DIServiceHost(Type serviceType, 
                         </span><span style="color: #0000FF; ">params</span><span style="color: #000000; "> Uri[] baseAddresses) 
        : </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">(serviceType, baseAddresses) 
    { }

    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">void</span><span style="color: #000000; "> OnOpening()
    {
        Description.Behaviors.Add(</span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceBehavior());
        </span><span style="color: #0000FF; ">base</span><span style="color: #000000; ">.OnOpening();
    }
}

</span><span style="color: #0000FF; ">public</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">class</span><span style="color: #000000; "> DIServiceHostFactory : ServiceHostFactory
{
    </span><span style="color: #0000FF; ">protected</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">override</span><span style="color: #000000; "> ServiceHost CreateServiceHost(
            Type serviceType, Uri[] baseAddresses)
    {
        </span><span style="color: #0000FF; ">return</span><span style="color: #000000; "> </span><span style="color: #0000FF; ">new</span><span style="color: #000000; "> DIServiceHost(serviceType, baseAddresses);
    }
}</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>The custom ServiceHostFactory class can now be used in the ServiceHost file required when doing IIS hosting:</p>

<p>
  <div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:96b67456-7704-422c-b22f-8dda187e6729" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><pre style="background-color:White;;overflow: auto;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000; ">&lt;%</span><span style="color: #000000; ">@ ServiceHost Language</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">C#</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Debug</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">true</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Service</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.MyWindsorService</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> 
                Factory</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">WindsorService.DIServiceHostFactory</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">
                CodeBehind</span><span style="color: #000000; ">=</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; ">MyWindsorService.svc.cs</span><span style="color: #000000; ">&quot;</span><span style="color: #000000; "> </span><span style="color: #000000; ">%&gt;</span></div></pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>

<p>There is also another way for achieving this that I will be investigating the next week or so using the <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html" target="_blank">WCF Integration Facility</a> for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk. </p>

<p>If you have any thoughts, improvements or suggestions I'm glad to hear them from you, my dear reader. It's the only way I'll ever learn :-). </p>

<p>Till next time.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/18/integrating-castle-windsor-and-nhibernate-with-wcf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>WCF friction</title>
		<link>http://elegantcode.com/2008/05/13/wcf-friction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-friction</link>
		<comments>http://elegantcode.com/2008/05/13/wcf-friction/#comments</comments>
		<pubDate>Tue, 13 May 2008 18:10:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/05/13/wcf-friction/</guid>
		<description><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception: System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly. This is really helpful, isn't it? Fortunately there is some [...]]]></description>
			<content:encoded><![CDATA[Today I spent some time (thank God no more than 15 minutes) tracking down a WCF issue from hell. Every time I made a call to the service I got the following exception:

<em>System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly.</em>

This is really helpful, isn't it? Fortunately there is some tool that helped me out a great deal: <a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" target="_blank">Service Trace Viewer Tool (SvcTraceViewer.exe)</a>. Turns out that I forgot to place a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract</a> attribute on one of my DTO objects.

Why am I too stupid to deduce this from the exception message in the first place?]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/05/13/wcf-friction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Demonstrating WCF: Beyond the endpoints</title>
		<link>http://elegantcode.com/2008/04/04/demonstrating-wcf-beyond-the-endpoints/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=demonstrating-wcf-beyond-the-endpoints</link>
		<comments>http://elegantcode.com/2008/04/04/demonstrating-wcf-beyond-the-endpoints/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 13:40:52 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/04/demonstrating-wcf-beyond-the-endpoints/</guid>
		<description><![CDATA[Yesterday evening, some team members and myself went to a session about Demonstrating WCF: Beyond the endpoints. The speaker was nobody less than Juval Lowy of IDesign. I'm not particular a newbie when it comes to WCF (although this post lets you believe otherwise), I really had a nice time. It's very clear that Juval [...]]]></description>
			<content:encoded><![CDATA[Yesterday evening, some team members and myself went to a session about <a TARGET="_blank" HREF="http://visug.be/Passedevents/WCFBeyondtheendpoints/tabid/80/Default.aspx">Demonstrating WCF: Beyond the endpoints</a>. The speaker was nobody less than <a TARGET="_blank" HREF="http://www.idesign.net/idesign/DesktopDefault.aspx?tabid=5&amp;tabindex=3">Juval Lowy</a> of <a TARGET="_blank" HREF="http://www.idesign.net/idesign/desktopdefault.aspx">IDesign</a>. I'm not particular a newbie when it comes to WCF (although <a TARGET="_blank" HREF="http://vanryswyckjan.blogspot.com/2008/02/wcf-security.html">this post</a> lets you believe otherwise), I really had a nice time. It's very clear that Juval is a trained speaker. However, the overall message of WCF as a silver bullet didn't quite catch on to me. Juval is a really smart guy. Therefore, he should know better :-). There are no silver bullets and no universal truths. I must admit that Microsoft did a remarkable job with the first version of WCF. One would almost believe that Scott Gu had something to do with it. But at the end of the road, WCF is one of the many tools in a developers tool bag. Tools can only take you that far but not to the end.  Again, I had a really nice time. Kudos to the <a TARGET="_blank" HREF="http://www.visug.be/">Belgian Visual Studio User Group</a>.]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/04/demonstrating-wcf-beyond-the-endpoints/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

