<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-6922092318950708456</atom:id><lastBuildDate>Fri, 01 Nov 2024 11:06:23 +0000</lastBuildDate><category>.NET</category><category>NHibernate</category><category>.NET 4 Client Profile</category><category>BehaviorExtensionElement</category><category>IDispatchMessageInspector</category><category>MVC</category><category>StructureMap</category><category>WCF</category><category>WCF dependency injection</category><category>assembly</category><category>discriminator</category><category>reference</category><category>return-discriminator</category><category>stored procedure</category><title>Scott Griffin</title><description>Please don&#39;t kick the frowning people.</description><link>http://www.sgriffinusa.com/</link><managingEditor>noreply@blogger.com (Scott Griffin)</managingEditor><generator>Blogger</generator><openSearch:totalResults>4</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6922092318950708456.post-2478776029580506902</guid><pubDate>Wed, 02 Feb 2011 17:18:00 +0000</pubDate><atom:updated>2012-03-14T13:22:32.849-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.NET</category><category domain="http://www.blogger.com/atom/ns#">BehaviorExtensionElement</category><category domain="http://www.blogger.com/atom/ns#">StructureMap</category><category domain="http://www.blogger.com/atom/ns#">WCF dependency injection</category><title>Setting up WCF to use StructureMap</title><description>As I &lt;a href=&quot;http://www.sgriffinusa.com/2011/01/using-nhibernate-with-windows.html&quot;&gt;previously posted&lt;/a&gt;, I recently deployed a new web service using &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms735119(v=vs.90).aspx&quot;&gt;WCF&lt;/a&gt;.  My team is using &lt;a href=&quot;http://nhforge.org/Default.aspx&quot;&gt;NHibernate&lt;/a&gt; as our ORM and using &lt;a href=&quot;http://structuremap.net/structuremap/&quot;&gt;StructureMap&lt;/a&gt; to handle &lt;a href=&quot;http://martinfowler.com/articles/injection.html&quot;&gt;inversion of control and dependency injection&lt;/a&gt;.  Obviously, we do not want to reinvent the wheel when deploying a WCF service so we needed to have StructureMap handle dependency injection for us.  &lt;a href=&quot;http://www.lostechies.com/blogs/jimmy_bogard/default.aspx&quot;&gt;Jimmy Bogard&lt;/a&gt; came to our rescue with a &lt;a href=&quot;http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/29/integrating-structuremap-with-wcf.aspx&quot;&gt;post&lt;/a&gt; detailing how this can be done.  However, there are a few things that can be trimmed from his example and a way to setup the service to work for all services in a project.   The first thing that needs to be created is an implementation of &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx&quot;&gt;IInstanceProvider&lt;/a&gt;.    &lt;pre class=&quot;prettyprint&quot;&gt;public class StructureMapInstanceProvider : IInstanceProvider
{
    private Type _serviceType;

    public StructureMapInstanceProvider(Type serviceType)
    {
        this._serviceType = serviceType;
    }

    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        return ObjectFactory.GetInstance(_serviceType);
    }

    public object GetInstance(InstanceContext instanceContext)
    {
        return this.GetInstance(instanceContext, null);
    }

    public void ReleaseInstance(InstanceContext instanceContext, object instance)
    {
        //No cleanup required
    }
}
&lt;/pre&gt;This is almost verbatim from Jimmy&#39;s post.  So now we have a way that WCF can instantiate objects.  We just need to tell WCF about it.  This can be done by implementing the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx&quot;&gt;IServiceBehavior &lt;/a&gt;interface.  Again, we use Jimmy&#39;s code:  &lt;pre class=&quot;prettyprint&quot;&gt;public class StructureMapServiceBehavior : IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription desc, ServiceHostBase host)
    {
        foreach (ChannelDispatcherBase cdb in host.ChannelDispatchers)
        {
            ChannelDispatcher cd = cdb as ChannelDispatcher;
            if (cd != null)
            {
                foreach (EndpointDispatcher ed in cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider = 
                        new StructureMapInstanceProvider(desc.ServiceType);
                }
            }
        }
    }

    public void AddBindingParameters(ServiceDescription desc, ServiceHostBase host,  
                                     Collection&lt;serviceendpoint&gt; endpoints, 
                                     BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription desc, ServiceHostBase host)
    {
    }
}
&lt;/pre&gt;This ties our IInstanceProvider to every endpoint that we expose via our service.  Jimmy then recommends extending &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx&quot;&gt;ServiceHost &lt;/a&gt;and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory.aspx&quot;&gt;ServiceHostFactory&lt;/a&gt; and using those classes to attach the Factory to each service.  I wanted to be able to configure this behavior once for the entire project.  So I modified the StructureMapServiceBehavior class to extend &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.behaviorextensionelement.aspx&quot;&gt;BehaviorExtensionElement&lt;/a&gt;.  This forced me to implement the following methods:  &lt;pre class=&quot;prettyprint&quot;&gt;public class StructureMapInstanceProvider : IInstanceProvider
{
...
public override Type BehaviorType
{
    get { return this.GetType(); }
}

protected override object CreateBehavior()
{
    ObjectFactory.Initialize(cfg =&gt;
    {
        cfg.Scan(scan =&gt;
        {
            scan.WithDefaultConventions();
        });
    });
    return this;
}
...
}
&lt;/pre&gt;This will initialize StructureMap.  With this complete, I can use StructureMapServiceBehavior as a behavior in my Web.Config.  &lt;pre class=&quot;prettyprint&quot;&gt;&amp;lt;system.serviceModel&gt;
    &amp;lt;behaviors&gt;
      &amp;lt;serviceBehaviors&gt;
        &amp;lt;behavior&gt;
          &amp;lt;StructureMapServiceBehavior /&gt;
        &amp;lt;/behavior&gt;
      &amp;lt;/serviceBehaviors&gt;
    &amp;lt;/behaviors&gt;
    &amp;lt;extensions&gt;
      &amp;lt;behaviorExtensions&gt;
        &amp;lt;add name=&quot;StructureMapServiceBehavior&quot; 
             type=&quot;Services.StructureMapServiceBehavior, Services, Version=1.0.0.0, Culture=neutral&quot;/&gt;
      &amp;lt;/behaviorExtensions&gt;
    &amp;lt;/extensions&gt;
  &amp;lt;/system.serviceModel&gt;
&lt;/pre&gt;Now StructureMap is loaded up and controls instantiation for any of my classes, just like in my MVC projects.  This can be used with any dependency injection framework.  Just modify the IInstanceProvider.GetInstance methods and the BehaviorExtensionElement.CreateBehavior method.</description><link>http://www.sgriffinusa.com/2011/02/setting-up-wcf-to-use-structuremap.html</link><author>noreply@blogger.com (Scott Griffin)</author><thr:total>9</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6922092318950708456.post-213461034834106036</guid><pubDate>Thu, 20 Jan 2011 21:03:00 +0000</pubDate><atom:updated>2011-11-28T12:05:10.320-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.NET</category><category domain="http://www.blogger.com/atom/ns#">.NET 4 Client Profile</category><category domain="http://www.blogger.com/atom/ns#">assembly</category><category domain="http://www.blogger.com/atom/ns#">reference</category><title>Application Can&#39;t Find References</title><description>For the past several hours I have been trying to understand why a C# console application would not build.  I&#39;m using Visual Studio 2010.  I have several other console applications that are working properly.  However, this one kept claiming that it could not find two custom assemblies that I had referenced.  I was getting 
&lt;br /&gt;
&lt;blockquote class=&quot;error&quot;&gt;
The type or namespace name &#39;&lt;a href=&quot;http://structuremap.net/structuremap/&quot;&gt;StructureMap&lt;/a&gt;&#39; could not be found (are you missing a using directive or an assembly reference?)
&lt;/blockquote&gt;
Of course, I checked repeatedly that the assemblies were in fact referenced.  I even went as far as deleting and recreating the project, all to no avail.  

I finally found a &lt;a href=&quot;http://stackoverflow.com/q/3304741/71519&quot;&gt;stackoverflow post&lt;/a&gt; that addressed the problem.  Turns out my custom assemblies are compiled targeting the .NET 4 Framework.  My console application was only targeting the .NET 4 Client Profile.  This caused the console application to lose track of the custom assemblies.  Extremely frustrating as the error message was not indicative of the problem.  Glad it was an easy fix though.</description><link>http://www.sgriffinusa.com/2011/01/application-cant-find-references.html</link><author>noreply@blogger.com (Scott Griffin)</author><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6922092318950708456.post-4667155672653187435</guid><pubDate>Thu, 06 Jan 2011 21:46:00 +0000</pubDate><atom:updated>2011-01-06T14:46:06.585-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.NET</category><category domain="http://www.blogger.com/atom/ns#">IDispatchMessageInspector</category><category domain="http://www.blogger.com/atom/ns#">MVC</category><category domain="http://www.blogger.com/atom/ns#">NHibernate</category><category domain="http://www.blogger.com/atom/ns#">WCF</category><title>Using NHibernate with Windows Communication Foundation (WCF)</title><description>Our team recently wanted to use WCF to create a new web service.  We are using nHibernate as our ORM.  We used &lt;a href=&quot;http://jeffreypalermo.com/blog/asp-net-mvc-httpmodule-registration-under-iis-integrated-mode-vs-classic-mode/&quot;&gt;a pattern described&lt;/a&gt; by Jeffery Palermo to integrate NHibernate into our MVC applications and were interested in doing something similar with WCF.  Unfortunately, this method doesn’t work for WCF, at least not without the overhead of turning on &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.aspnetcompatibilityrequirementsattribute.requirementsmode.aspx&quot;&gt;AspNetCompatibilityRequirementsMode&lt;/a&gt; (just typing that hurts a little.)  
In my research, I discovered the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.idispatchmessageinspector.aspx&quot;&gt;IDispatchMessageInspector&lt;/a&gt; interface.  This interface provides an AfterReceiveRequest and BeforeSendReply methods.  This will allow me to open an NHibernate session before the message is processed and close it just before my reply is sent to the consumer.  Additionally, because it is an interface, I can simply have my exisiting HttpModule implementation extend the IDispatchMessageInspector interface.  My methods are implemented as follows:
&lt;pre class=&quot;prettyprint&quot;&gt;
public object AfterReceiveRequest(ref Message req, IClientChannel chan, InstanceContext context)
{
    context_BeginRequest(null, null);
    return null;
}
&lt;/pre&gt;
and
&lt;pre class=&quot;prettyprint&quot;&gt;
public void BeforeSendReply(ref Message reply, object correlationState)
{
    context_EndRequest(null, null);
}
&lt;/pre&gt;
This allows me to use the same code as my HttpModule.  All that is left to do is tie the IDispatchMessageInspector to my service.  We can do this by implementing the IServiceBehavior interface, we’ll call the class NHibernateWcfBehaviorExtension.  I was lazy and did this on the same HttpModule class, multiple inheritance is awesome!  The IServiceBehavior requires three methods, only one will actually do anything:
&lt;pre class=&quot;prettyprint&quot;&gt;
public void ApplyDispatchBehavior(ServiceDescription descriptoin, ServiceHostBase hostBase)
{
    foreach (ChannelDispatcher cd in hostBase.ChannelDispatchers)
    {
        foreach (EndpointDispatcher ed in cd.Endpoints)
        {
            ed.DispatchRuntime.MessageInspectors.Add(this);
        }
    }
}
&lt;/pre&gt;
This will load the message inspector on each of the service’s endpoints.  Now all we need to do is tell WCF about this IServiceBehavior.  This can be done by extending  BehaviorExtensionElement.  We’ll call our implementation NHibernateSessionStarter .  This class should return the type and a new instance of NHibernateWcfBehaviorExtension.  Once we have the BehaviorExtensionElement, we can use it to tell WCF about our IServiceBehavior in the Web.Config.  
&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;system.serviceModel&gt;
  &amp;lt;behaviors&gt;
    &amp;lt;serviceBehaviors&gt;
      &amp;lt;behavior&gt;
        &amp;lt;serviceMetadata httpGetEnabled=&quot;true&quot;/&gt;
        &amp;lt;serviceDebug includeExceptionDetailInFaults=&quot;true&quot;/&gt;
        &amp;lt;!-- Service behavior is added here. --&gt;
        &amp;lt;NHibernateSessionStarter /&gt;
      &amp;lt;/behavior&gt;
    &amp;lt;/serviceBehaviors&gt;
  &amp;lt;/behaviors&gt;
  &amp;lt;extensions&gt;
    &amp;lt;behaviorExtensions&gt;
      &amp;lt;!-- Service behavior is defined here. --&gt;
      &amp;lt;add name=&quot;NHibernateSessionStarter&quot; type=&quot;Infrastructure.NHibernateWcfBehaviorExtension, Infrastructure, Version=1.0.0.0, Culture=neutral&quot; /&gt;
    &amp;lt;/behaviorExtensions&gt;
  &amp;lt;/extensions&gt;
  &amp;lt;serviceHostingEnvironment multipleSiteBindingsEnabled=&quot;true&quot; /&gt;
&amp;lt;/system.serviceModel&gt;
&lt;/pre&gt;
Voila, WCF configured to use the same NHibernate startup and cleanup as our MVC apps.</description><link>http://www.sgriffinusa.com/2011/01/using-nhibernate-with-windows.html</link><author>noreply@blogger.com (Scott Griffin)</author><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6922092318950708456.post-5297663249514728269</guid><pubDate>Thu, 23 Dec 2010 15:03:00 +0000</pubDate><atom:updated>2010-12-23T08:28:03.363-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.NET</category><category domain="http://www.blogger.com/atom/ns#">discriminator</category><category domain="http://www.blogger.com/atom/ns#">NHibernate</category><category domain="http://www.blogger.com/atom/ns#">return-discriminator</category><category domain="http://www.blogger.com/atom/ns#">stored procedure</category><title>Using an NHibernate discriminator with a stored procedure</title><description>&lt;p&gt;Recently I needed to split the results of a stored procedure into one of two classes based on one of the columns using NHibernate.  Having recently discovered discriminators, I applied the discriminator tag to my mapping file and created my subclasses.  (I&#39;ve changed the names of the classes and columns, so please excuse the lame example.)  I want to generate either a teacher or a student object for a specified semester from each row in the stored procedures result set.  Teacher if the class_room value is not null, student otherwise.  Initially I tried to accomplish this using a discriminator formula.&lt;/p&gt;

&lt;pre class=&#39;prettyprint&#39;&gt;
&amp;lt;hibernate-mapping  xmlns=&quot;urn:nhibernate-mapping-2.2&quot; assembly=&quot;Core&quot; namespace=&quot;Core&quot;&gt;
  &amp;lt;class name=&quot;AbstractPerson&quot; abstract=&quot;true&quot;&gt;
    &amp;lt;id name=&quot;Id&quot; /&gt;
    &amp;lt;property name=&quot;FirstName&quot; /&gt;
    &amp;lt;property name=&quot;LastName&quot; /&gt;
 &amp;lt;discriminator formula=&quot;case when class_room is null then 1 else 0 end&quot; /&gt;
    &amp;lt;subclass discriminator-value=&quot;0&quot; name=&quot;Student&quot;&gt;
      &amp;lt;property name=&quot;DormRoom&quot; /&gt;
    &amp;lt;/subclass&gt;
    &amp;lt;subclass discriminator-value=&quot;1&quot; name=&quot;Teacher&quot;&gt;
      &amp;lt;property name=&quot;Classroom&quot; /&gt;
    &amp;lt;/subclass&gt;
  &amp;lt;/class&gt;
  &amp;lt;sql-query name=&quot;GetPeopleWithLocation&quot; callable=&quot;true&quot;&gt;
    &amp;lt;return class=&quot;AbstractPerson&quot;&gt;
      &amp;lt;return-property name=&quot;FirstName&quot; column=&quot;first_name&quot; /&gt;
      &amp;lt;return-property name=&quot;LastName&quot; column=&quot;last_name&quot; /&gt;
      &amp;lt;return-property name=&quot;DormRoom&quot; column=&quot;dorm_room&quot; /&gt;
   &amp;lt;return-property name=&quot;ClassRoom&quot; column=&quot;class_room&quot; /&gt;
    &amp;lt;/return&gt;
    exec get_person_location :semester_id
  &amp;lt;/sql-query&gt;
&amp;lt;/hibernate-mapping&gt;
&lt;/pre&gt;

&lt;p&gt;
Of course, I had put the discriminator in the incorrect location and got the following error:

&lt;blockquote class=&quot;error&quot;&gt;
XML validation error: The element &#39;class&#39; in namespace &#39;urn:nhibernate-mapping-2.2&#39; has invalid child element &#39;discriminator&#39; in namespace &#39;urn:nhibernate-mapping-2.2&#39;
&lt;/blockquote&gt;

Doing some research, I realized that the discriminator tag needs to be directly under the id element.  I moved it and executed my test again (you are doing TDD right?).
&lt;/p&gt;
&lt;p&gt;
This time the query ran, but I got a rather cryptic error:

&lt;blockquote class=&quot;error&quot;&gt;
[SQL: exec get_person_location :semester_id] ---&gt; System.IndexOutOfRangeException: clazz_0_
&lt;/blockquote&gt;

Based on previous experience with discriminators and some research, I believe this error was caused because NHibernate is attempting to add the discriminator formula to the sql statement that is being executed.  This is obviously problematic when using a stored procedure. Back to the drawing board.  
&lt;/p&gt;

&lt;p&gt;
I continued researching and finally found the &lt;a href=&quot;http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#propertyresults&quot;&gt;return-discriminator tag from the Hibernate documentation&lt;/a&gt;.  This tag can be used in the return class to specify which column should be used as the discriminator.  Now that sounds promising!  Another visit to the mapping file yeilded another error:

&lt;blockquote class=&quot;error&quot;&gt;
XML validation error: The element &#39;return&#39; in namespace &#39;urn:nhibernate-mapping-2.2&#39; has invalid child element &#39;return-discriminator&#39; in namespace &#39;urn:nhibernate-mapping-2.2&#39;.
&lt;/blockquote&gt;

I had placed the return-discriminator tag at the end of the return class. It must be the first element after the return tag.  
&lt;/p&gt;

&lt;p&gt;
The final mapping file looks like this:

&lt;pre class=&quot;prettyprint&quot;&gt;
&amp;lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot; assembly=&quot;Core&quot; namespace=&quot;Core&quot;&gt;
  &amp;lt;class name=&quot;AbstractPerson&quot; abstract=&quot;true&quot;&gt;
    &amp;lt;id name=&quot;Id&quot; /&gt;
 &lt;&amp;lt;discriminator column=&quot;class_room&quot; /&gt;
    &amp;lt;property name=&quot;FirstName&quot; /&gt;
    &amp;lt;property name=&quot;LastName&quot; /&gt;
    &amp;lt;subclass discriminator-value=&quot;null&quot; name=&quot;Student&quot;&gt;
      &amp;lt;property name=&quot;DormRoom&quot; /&gt;
    &amp;lt;/subclass&gt;
    &amp;lt;subclass discriminator-value=&quot;not null&quot; name=&quot;Teacher&quot;&gt;
      &amp;lt;property name=&quot;ClassRoom&quot; /&gt;
    &amp;lt;/subclass&gt;
  &amp;lt;/class&gt;
  &amp;lt;sql-query name=&quot;GetPeopleWithLocation&quot; callable=&quot;true&quot;&gt;
    &amp;lt;return class=&quot;AbstractPerson&quot;&gt;
      &amp;lt;return-discriminator column=&quot;class_room&quot; /&gt;
      &amp;lt;return-property name=&quot;FirstName&quot; column=&quot;first_name&quot; /&gt;
      &amp;lt;return-property name=&quot;LastName&quot; column=&quot;last_name&quot; /&gt;
      &amp;lt;return-property name=&quot;DormRoom&quot; column=&quot;dorm_room&quot; /&gt;
   &amp;lt;return-property name=&quot;ClassRoom&quot; column=&quot;class_room&quot; /&gt;
    &amp;lt;/return&gt;
    exec get_person_location :semester_id
  &amp;lt;/sql-query&gt;
&amp;lt;/hibernate-mapping&gt;
&lt;/pre&gt;
&lt;/p&gt;
&lt;p&gt;
Hope this saves someone a few minutes.
&lt;/p&gt;</description><link>http://www.sgriffinusa.com/2010/12/using-nhibernate-discriminator-with.html</link><author>noreply@blogger.com (Scott Griffin)</author><thr:total>2</thr:total></item></channel></rss>