<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Tony Sneed&#039;s Blog</title>
	<atom:link href="http://blog.tonysneed.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tonysneed.com</link>
	<description>A glimpse into the lives of Tony &#38; Zuzana Sneed</description>
	<lastBuildDate>Sat, 26 May 2012 21:40:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.tonysneed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/ccbe733658db4b886c4776fed57fcd38?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Tony Sneed&#039;s Blog</title>
		<link>http://blog.tonysneed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.tonysneed.com/osd.xml" title="Tony Sneed&#039;s Blog" />
	<atom:link rel='hub' href='http://blog.tonysneed.com/?pushpress=hub'/>
		<item>
		<title>Decouple WCF Services from their DI Container with Common Instance Factory</title>
		<link>http://blog.tonysneed.com/2012/05/26/decouple-wcf-services-from-their-di-container-with-common-instance-factory/</link>
		<comments>http://blog.tonysneed.com/2012/05/26/decouple-wcf-services-from-their-di-container-with-common-instance-factory/#comments</comments>
		<pubDate>Sat, 26 May 2012 21:40:36 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=429</guid>
		<description><![CDATA[In my last blog post I introduced the Common Instance Factory, which I built as an alternative to Common Service Locator to reduce coupling between an application and a Dependency Injection (DI) container.&#160; Unlike the Common Service Locator (CSL), the &#8230; <a href="http://blog.tonysneed.com/2012/05/26/decouple-wcf-services-from-their-di-container-with-common-instance-factory/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=429&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://instancefactory.codeplex.com/"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;float:left;border-top:0;border-right:0;padding-top:0;" title="instance-factory-logo2" border="0" alt="instance-factory-logo2" align="left" src="http://tonysneed.files.wordpress.com/2012/05/instance-factory-logo2.jpg?w=181&h=139" width="181" height="139"></a>In my <a href="http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/">last blog post</a> I introduced the <a href="http://instancefactory.codeplex.com/">Common Instance Factory</a>, which I built as an alternative to <a href="http://commonservicelocator.codeplex.com/">Common Service Locator</a> to reduce coupling between an application and a Dependency Injection (DI) container.&nbsp; Unlike the Common Service Locator (CSL), the Common Instance Factory (CIF) discourages the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">service location anti-pattern</a> by using the <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">abstract factory design pattern</a>.</p>
<p>I would venture to say that in many cases, introducing this additional layer of abstraction is not always necessary.&nbsp; If you are careful to register your types early in the startup of your application and avoid referencing the DI container from within your types (which is where the service location ant-pattern rears its ugly head), then selecting a DI container and sticking with it might be perfectly appropriate.&nbsp; And I would certainly not use CIF for unit tests (or even some integration tests), where you need to leverage features of the DI container that are not exposed via the factory interface.</p>
<p>There are other situations, however, when wrapping the DI container with the CIF will give you the kind of decoupling and flexibility you want in your application architecture. This layer of abstraction can be especially advantageous, for example, when building <a href="http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework">ASP.NET apps</a> or <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation">WCF services</a> where <a href="http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison">performance</a> is a critical factor. In this case, you might want to use a super-fast DI container, such as <a href="http://simpleinjector.codeplex.com/">SimpleInjector</a>, for the application while leveraging a full-featured DI container, just as <a href="http://www.ninject.org/">Ninject</a>, for unit testing.</p>
<p>The NuGet package, <a href="http://nuget.org/packages/CommonInstanceFactory.Extensions.Wcf">CommonInstanceFactory.Extensions.Wcf</a>, provides the building blocks for hosting WCF services which are decoupled from a particular DI container. The first component is the <strong>InjectedInstanceProvider</strong>, which implements the WCF interface, <a href="http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx">IInstanceProvider</a>, using ICommonInstanceFactory to retrieve and release instances from the DI container (see my <a href="http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/">prior blog post</a> for more information on ICommonInstanceFactory).</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">InjectedInstanceProvider</span>&lt;TServiceType&gt; : <span style="color:#2b91af;">IInstanceProvider
    </span><span style="color:blue;">where </span>TServiceType : <span style="color:blue;">class
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TServiceType&gt; _container;

    <span style="color:blue;">public </span>InjectedInstanceProvider(<span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TServiceType&gt; container)
    {
        _container = container;
    }

    <span style="color:blue;">public object </span>GetInstance(<span style="color:#2b91af;">InstanceContext </span>instanceContext, <span style="color:#2b91af;">Message </span>message)
    {
        <span style="color:blue;">return </span>GetInstance(instanceContext);
    }

    <span style="color:blue;">public object </span>GetInstance(<span style="color:#2b91af;">InstanceContext </span>instanceContext)
    {
        TServiceType service = _container.GetInstance();
        <span style="color:blue;">return </span>service;
    }

    <span style="color:blue;">public void </span>ReleaseInstance(<span style="color:#2b91af;">InstanceContext </span>instanceContext, <span style="color:blue;">object </span>instance)
    {
        <span style="color:blue;">var </span>service = instance <span style="color:blue;">as </span>TServiceType;
        <span style="color:blue;">if </span>(service != <span style="color:blue;">null</span>)
        {
            <span style="color:blue;">try
            </span>{
                _container.ReleaseInstance(service);
            }
            <span style="color:blue;">finally
            </span>{
                <span style="color:blue;">var </span>disposable = instance <span style="color:blue;">as </span><span style="color:#2b91af;">IDisposable</span>;
                <span style="color:blue;">if </span>(disposable != <span style="color:blue;">null</span>)
                {
                    disposable.Dispose();
                }
            }
        }
    }
}</pre>
<p>If the underlying DI container does not implement ReleaseInstance, no harm no foul. Notice how ReleaseInstance checks to see if the service type implements IDisposable and, if so, calls Dispose on it. (This behavior happens to be missing from Ninject’s WCF extension, but CIF provides the correct implementation.)</p>
<p>Next, the CIF extension for WCF supplies an <strong>InjectedServiceBehavior</strong>, whose job it is to plug the InjectedInstanceProvider into the WCF pipeline.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">InjectedServiceBehavior</span>&lt;TServiceType&gt; : <span style="color:#2b91af;">IServiceBehavior
    </span><span style="color:blue;">where </span>TServiceType : <span style="color:blue;">class
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TServiceType&gt; _container;

    <span style="color:blue;">public </span>InjectedServiceBehavior(<span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TServiceType&gt; container)
    {
        _container = container;
    }

    <span style="color:blue;">public void </span>ApplyDispatchBehavior(<span style="color:#2b91af;">ServiceDescription </span>serviceDescription, <span style="color:#2b91af;">ServiceHostBase </span>serviceHostBase)
    {
        <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">ChannelDispatcherBase </span>cdb <span style="color:blue;">in </span>serviceHostBase.ChannelDispatchers)
        {
            <span style="color:blue;">var </span>cd = cdb <span style="color:blue;">as </span><span style="color:#2b91af;">ChannelDispatcher</span>;
            <span style="color:blue;">if </span>(cd != <span style="color:blue;">null</span>)
            {
                <span style="color:blue;">foreach </span>(<span style="color:#2b91af;">EndpointDispatcher </span>ed <span style="color:blue;">in </span>cd.Endpoints)
                {
                    ed.DispatchRuntime.InstanceProvider
                        = <span style="color:blue;">new </span><span style="color:#2b91af;">InjectedInstanceProvider</span>&lt;TServiceType&gt;(_container);
                }
            }
        }
    }
}</pre>
<p>Lastly, there is the <strong>InjectedServiceHostFactory</strong> abstract class, which container-specific adapters will need to implement to initialize a container and return a container-specific ServiceHost.</p>
<pre class="code"><span style="color:blue;">public abstract class </span><span style="color:#2b91af;">InjectedServiceHostFactory</span>&lt;TContainer&gt; : <span style="color:#2b91af;">ServiceHostFactory
    </span><span style="color:blue;">where </span>TContainer : <span style="color:blue;">class
</span>{
    <span style="color:blue;">protected abstract </span>TContainer CreateContainer();

    <span style="color:blue;">protected abstract </span><span style="color:#2b91af;">ServiceHost </span>CreateInjectedServiceHost
        (TContainer container, <span style="color:#2b91af;">Type </span>serviceType, <span style="color:#2b91af;">Uri</span>[] baseAddresses);

    <span style="color:blue;">protected override </span><span style="color:#2b91af;">ServiceHost </span>CreateServiceHost(<span style="color:#2b91af;">Type </span>serviceType, <span style="color:#2b91af;">Uri</span>[] baseAddresses)
    {
        TContainer container = CreateContainer();
        <span style="color:#2b91af;">ServiceHost </span>serviceHost = CreateInjectedServiceHost
            (container, serviceType, baseAddresses);
        <span style="color:blue;">return </span>serviceHost;
    }
}</pre>
<p>Here is an example of a class that extends InjectedServiceHostFactory by implementing its abstract methods.&nbsp; This class would most likely reside in a WCF host (such as a web project) or an assembly referenced by a host, because it needs to initialize the container by registering dependencies that are specific to the application – in this case via the GreetingModule.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectServiceHostFactory </span>: <span style="color:#2b91af;">InjectedServiceHostFactory</span>&lt;<span style="color:#2b91af;">IKernel</span>&gt;
{
    <span style="color:blue;">protected override </span><span style="color:#2b91af;">IKernel </span>CreateContainer()
    {
        <span style="color:#2b91af;">IKernel </span>container = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>();
        container.Load&lt;<span style="color:#2b91af;">GreetingModule</span>&gt;();
        <span style="color:blue;">return </span>container;
    }

    <span style="color:blue;">protected override </span><span style="color:#2b91af;">ServiceHost </span>CreateInjectedServiceHost
        (<span style="color:#2b91af;">IKernel </span>container, <span style="color:#2b91af;">Type </span>serviceType, <span style="color:#2b91af;">Uri</span>[] baseAddresses)
    {
        <span style="color:#2b91af;">ServiceHost </span>serviceHost = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHost
            </span>(container, serviceType, baseAddresses);
        <span style="color:blue;">return </span>serviceHost;
    }
}</pre>
<p>Here is how <a href="https://nuget.org/packages/CommonInstanceFactory.Extensions.Wcf.Ninject">CommonInstanceFactory.Extensions.Wcf.Ninject</a> extends ServiceHost with by providing <strong>NinjectServiceHost</strong>, which accepts a container to create a NinjectInstanceFactory and adds the InjectedServiceBehavior to the ServiceHost’s Description.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectServiceHost</span>&lt;TServiceType&gt; : <span style="color:#2b91af;">ServiceHost
    </span><span style="color:blue;">where </span>TServiceType : <span style="color:blue;">class
</span>{
    <span style="color:blue;">public </span>NinjectServiceHost(<span style="color:#2b91af;">IKernel </span>container, <span style="color:#2b91af;">Type </span>serviceType, <span style="color:blue;">params </span><span style="color:#2b91af;">Uri</span>[] baseAddresses)
        : <span style="color:blue;">base</span>(serviceType, baseAddresses)
    {
<span style="color:green;">        </span><span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TServiceType&gt; instanceFactory
            = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectInstanceFactory</span>&lt;TServiceType&gt;(container);
<span style="color:green;">        </span>Description.Behaviors.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">InjectedServiceBehavior</span>&lt;TServiceType&gt;(instanceFactory));
    }
}</pre>
<p>Lastly, here is an example of a Service.svc file which references the container-specific <strong>NinjectServiceHostFactory</strong>.&nbsp; (The non-generic version of NinjectServiceHost uses a little reflection magic to instantiate the generic NinjectInstanceFactory&lt;TServiceType&gt;.)</p>
<pre class="code"><span style="background:yellow;">&lt;%</span><span style="color:blue;">@ </span><span style="color:maroon;">ServiceHost </span><span style="color:red;">Factory</span><span style="color:blue;">="CommonInstanceFactory.Sample.Hosting.Web.ServiceHostFactories.NinjectServiceHostFactory" 
                </span><span style="color:red;">Service</span><span style="color:blue;">="CommonInstanceFactory.Sample.Services.GreetingService" </span><span style="background:yellow;">%&gt;</span></pre>
<p>When you want to change from one DI container to another, all you need to do is replace the Factory attribute with the ServiceHostFactory of the new container.&nbsp; For example, here is a Service.svc which references the <strong>SimpleInjectorServiceHostFactory</strong>.</p>
<pre class="code"><span style="background:yellow;">&lt;%</span><span style="color:blue;">@ </span><span style="color:maroon;">ServiceHost </span><span style="color:red;">Factory</span><span style="color:blue;">="CommonInstanceFactory.Sample.Hosting.Web.ServiceHostFactories.SimpleInjectorServiceHostFactory" 
                </span><span style="color:red;">Service</span><span style="color:blue;">="CommonInstanceFactory.Sample.Services.GreetingService" </span><span style="background:yellow;">%&gt;</span></pre>
<p>If you have a non-web host, such as a Windows Service, you won’t need to worry about wiring up a container-specific ServiceHostFactory at all.&nbsp; Instead, you can simply initialize the container yourself and pass it directly to the constructor of the container-specific ServiceHost.</p>
<pre class="code"><span style="color:#2b91af;">ServiceHost </span>serviceHost;
<span style="color:blue;">var </span>serviceBaseAddress = <span style="color:blue;">new </span><span style="color:#2b91af;">Uri</span>(<span style="color:#a31515;">"http://localhost:8000/GreetingService"</span>);
<span style="color:blue;">switch </span>(containerType)
{
    <span style="color:blue;">case </span><span style="color:#2b91af;">ContainerType</span>.Ninject:
        serviceHost = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHost</span>&lt;<span style="color:#2b91af;">GreetingService</span>&gt;
            (CreateNinjectContainer(), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">GreetingService</span>), serviceBaseAddress);
        <span style="color:blue;">break</span>;
    <span style="color:blue;">case </span><span style="color:#2b91af;">ContainerType</span>.SimpleInjector:
        serviceHost = <span style="color:blue;">new </span><span style="color:#2b91af;">SimpleInjectorServiceHost</span>&lt;<span style="color:#2b91af;">GreetingService</span>&gt;
            (CreateSimpleInjectorContainer(), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">GreetingService</span>), serviceBaseAddress);
        <span style="color:blue;">break</span>;
}</pre>
<p>Using the <a href="http://instancefactory.codeplex.com/">Common Instance Factory</a>, switching DI containers is relatively painless, and you’ll get a layer of abstraction from the DI container that will help decouple your WCF services from any particular container.&nbsp; To get CIF, download the <a href="https://nuget.org/packages?q=commonintancefactory">NuGet CIF packages</a>. To see examples of using CIF with WCF extensions, download <a href="http://instancefactory.codeplex.com/releases/view/88235">samples and source code</a> from the CIF CodePlex site. Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/429/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=429&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/05/26/decouple-wcf-services-from-their-di-container-with-common-instance-factory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/05/instance-factory-logo2.jpg" medium="image">
			<media:title type="html">instance-factory-logo2</media:title>
		</media:content>
	</item>
		<item>
		<title>Use Common Instance Factory to Abstract Away the Dependency Injection Container</title>
		<link>http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/</link>
		<comments>http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/#comments</comments>
		<pubDate>Wed, 23 May 2012 14:33:03 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=426</guid>
		<description><![CDATA[Download the Common Instance Factory with WCF Extensions here and is also available on NuGet. A while back I wrote a blog post on the Onion Architecture, an approach to building loosely-coupled applications where you can swap out particular components &#8230; <a href="http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=426&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the Common Instance Factory with WCF Extensions <a href="http://instancefactory.codeplex.com/">here</a> and is also available on <a href="https://nuget.org/packages?q=commonintancefactory">NuGet</a>.</em></p>
<p>A while back I wrote a blog post on the <a href="http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/">Onion Architecture</a>, an approach to building loosely-coupled applications where you can swap out particular components without affecting the rest of the application.&nbsp; They key to making it all work is the use of <a href="http://msdn.microsoft.com/en-us/magazine/cc163739.aspx">Dependency Injection</a>, also known as Inversion of Control, to delegate creation of types to an external container.&nbsp; There are various ways to implement dependency injection, but the most common is a technique called “constructor injection,” in which a class provides a constructor that accepts one or more interfaces as parameters.&nbsp; Concrete implementations of each interface are registered with the DI container and supplied to the constructor when a request for the type is made from the container.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">GreetingService </span>: <span style="color:#2b91af;">IGreetingService
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IGreetingRepository </span>_greetingRepository;

    <span style="color:blue;">public </span>GreetingService(<span style="color:#2b91af;">IGreetingRepository </span>greetingRepository)
    {
        _greetingRepository = greetingRepository;
    }

    <span style="color:blue;">public string </span>Greet(<span style="color:blue;">string </span>name)
    {
        <span style="color:blue;">string </span>greeting = _greetingRepository.GetGreeting();
        <span style="color:blue;">return string</span>.Format(<span style="color:#a31515;">"</span><span style="color:#3cb371;">{0} {1}</span><span style="color:#a31515;">"</span>, greeting, name);
    }
}</pre>
<p>In this example, an IGreetingRepository is passed to the GreetingService’s constructor.&nbsp; GreetingService doesn’t care how IGreetingRepository is implemented.&nbsp; It’s the job of the DI container to provide whichever implementation of IGreetingRepository was registered with the container.&nbsp; This promises the architect’s nirvana of <em>loose coupling</em>, because the GreetingService is abstracted away from the implementation of IGreetingRepository, which allows you to switch from one persistence stack to another without affecting parts of the application which depend on it.</p>
<p>Ah, but there’s a problem. You have to select a DI container from one of numerous proprietary and open-source products on the market and then marry yourself to it.&nbsp; <em>You are then tightly coupled to the DI container!&nbsp; </em>Now, there are some best practices when it comes to using a DI container, which make it less traumatic to switch from one to another, such as registering dependencies at the <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">composition root</a>, or entry point, of the application.&nbsp; Still, placing a layer of abstraction between your application and the DI container allows for greater flexibility, which is what loose-coupling is all about.</p>
<p>Until recently, I was content to select a DI container, based on its features and ease-of-use, and learn to live with it.&nbsp; Then I started looking at <a href="http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison">performance benchmarks</a> for various DI containers.&nbsp; It turnes out my favorite container, Ninject, was one of the worst performing.&nbsp; So it was time to look at switching to another container for the application I was writing.&nbsp; This didn’t mean, however, I had to jettison Ninject altogether.&nbsp; A lot of DI-specific code is needed for unit tests, where there is extensive mocking, and advanced features of a DI container such as Ninject come in handy.</p>
<p>When searching for a way to abstract away the DI container, the first solution I examined was the <a href="http://commonservicelocator.codeplex.com/">Common Service Locator</a>, built by Microsoft’s Patterns and Practices group back in 2008 with the source code posted on CodePlex.&nbsp; However, I found a couple of deficiencies. First, and most egregious, is that it is modeled as a service locator, rather than an abstract factory.&nbsp; In his article, <a href="http://martinfowler.com/articles/injection.html">Inversion of Control Containers and the Dependency Injection Pattern</a>, Martin Fowler describes some of the <a href="http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection">weaknesses</a> of the service locator <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">anti-pattern</a>.&nbsp; He states, “With a Service Locator every user of a service has a dependency to the locator,” and that “the locator can hide dependencies to other implementations.”</p>
<p>The problem arises when a class directly references the locator, using it to instantiate types it depends on, which creates a dependency on the locator and hides the actual dependencies of the class.&nbsp; While it is possible to use the Common Service Locator without falling into this trap, the base interface, IServiceLocator, is a <a href="http://blog.ploeh.dk/2010/11/01/PatternRecognitionAbstractFactoryOrServiceLocator.aspx">non-generic interface with a generic method</a> that allows you to create an infinite number of types, making it easier for classes to use it directly. </p>
<p>This was undoubtedly a design-decision by the MS team to achieve a wider adoption by making the Common Service Locator compatible with both dependency injection and service location frameworks. However, a cleaner alternative is the <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">abstract factory pattern</a>, which can be expressed as a generic interface with a method that only return instances of a single type.&nbsp; This discourages folks from using the factory for service location and instead promotes the dependency injection pattern described by Martin Fowler.</p>
<p>Another weakness of Common Service Locator is that it does not provide a <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">ReleaseInstance</a> method.&nbsp; Some containers manage the lifetime of instances internally and there needs to be a way to ask a container to release an instance under its control.</p>
<p>This led me to develop the <a href="http://instancefactory.codeplex.com/">Common Instance Factory</a>, as an alternative to the Common Service Locator, and to extend it with support for WCF services that are decoupled from any particular DI container.&nbsp; Notice it’s a “factory” versus “locator” and that it produces “instances” instead of “services” (while technically more accurate, I found the term “service” to be overused and sometimes misleading).&nbsp; Here is the root interface used for resolving instances.</p>
<p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TInstance&gt;
{
<span style="color:gray;">    </span>TInstance GetInstance();
<span style="color:gray;">    </span><span style="color:#2b91af;">IEnumerable</span>&lt;TInstance&gt; GetAllInstances();
<span style="color:gray;">    </span><span style="color:blue;">void </span>ReleaseInstance(TInstance instance);
}</pre>
<p>The base implementation is an abstract class with methods which container-specific adapters need to override.</p>
<pre class="code"><span style="color:blue;">public abstract class </span><span style="color:#2b91af;">CommonInstanceFactoryBase</span>&lt;TInstance&gt; : <span style="color:#2b91af;">ICommonInstanceFactory</span>&lt;TInstance&gt;
    <span style="color:blue;">where </span>TInstance : <span style="color:blue;">class
</span>{
<span style="color:gray;">    </span><span style="color:blue;">public </span>TInstance GetInstance()
    {
        <span style="color:blue;">return </span>InternalGetInstance();
    }

<span style="color:gray;">    </span><span style="color:blue;">public </span><span style="color:#2b91af;">IEnumerable</span>&lt;TInstance&gt; GetAllInstances()
    {
        <span style="color:blue;">return </span>InternalGetAllInstances();
    }

<span style="color:gray;">    </span><span style="color:blue;">public void </span>ReleaseInstance(TInstance instance)
    {
        InternalReleaseInstance(instance);
    }

<span style="color:gray;">    </span><span style="color:blue;">protected abstract </span>TInstance InternalGetInstance();
<span style="color:gray;">    </span><span style="color:blue;">protected abstract </span><span style="color:#2b91af;">IEnumerable</span>&lt;TInstance&gt; InternalGetAllInstances();
<span style="color:gray;">    </span><span style="color:blue;">protected abstract void </span>InternalReleaseInstance(TInstance instance);
}</pre>
<p>To start with, I’ve written two adapters, one for <a href="http://www.ninject.org/">Ninject</a> (slow but with a lot of features) and one for <a href="http://simpleinjector.codeplex.com/">SimpleInjector</a> (fast but with fewer features).&nbsp; The implementation of the abstract base class is quite straightforward, so there’s not much effort required to write adapters for other DI containers. (Stay tuned for more!)&nbsp; Here’s the Ninject adapter.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectInstanceFactory</span>&lt;TInstance&gt; : <span style="color:#2b91af;">CommonInstanceFactoryBase</span>&lt;TInstance&gt;
    <span style="color:blue;">where </span>TInstance : <span style="color:blue;">class
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IKernel </span>_container;

    <span style="color:blue;">public </span>NinjectInstanceFactory(<span style="color:#2b91af;">IKernel </span>container)
    {
        _container = container;
    }

    <span style="color:blue;">protected override </span>TInstance InternalGetInstance()
    {
        <span style="color:blue;">var </span>instance = _container.Get&lt;TInstance&gt;();
        <span style="color:blue;">return </span>instance;
    }

    <span style="color:blue;">protected override </span><span style="color:#2b91af;">IEnumerable</span>&lt;TInstance&gt; InternalGetAllInstances()
    {
        <span style="color:blue;">var </span>instances = _container.GetAll&lt;TInstance&gt;();
        <span style="color:blue;">return </span>instances;
    }

    <span style="color:blue;">protected override void </span>InternalReleaseInstance(TInstance instance)
    {
        _container.Release(instance);
    }
}</pre>
<p>To use it all you have to do is new up the NinjectInstanceFactory, supplying an initialized container to the constructor.&nbsp; Here is a unit test that demonstrates the usage.</p>
<pre class="code">[<span style="color:#2b91af;">TestFixture</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectAdapterTests
</span>{
    <span style="color:blue;">private </span><span style="color:#2b91af;">IKernel </span>_container;

    [<span style="color:#2b91af;">TestFixtureSetUp</span>]
    <span style="color:blue;">public void </span>TestSetup()
    {
        _container = <span style="color:blue;">new </span><span style="color:#2b91af;">StandardKernel</span>();
        _container.Load&lt;<span style="color:#2b91af;">GreetingModule</span>&gt;();
    }

    [<span style="color:#2b91af;">Test</span>]
    <span style="color:blue;">public void </span>Ninject_Adapter_Should_Get_GreetingService()
    {
        <span style="color:green;">// Arrange
        </span><span style="color:blue;">var </span>resolver = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectInstanceFactory</span>&lt;<span style="color:#2b91af;">GreetingService</span>&gt;(_container);

        <span style="color:green;">// Act
        </span><span style="color:blue;">var </span>greeter = resolver.GetInstance();
        <span style="color:blue;">string </span>greeting = greeter.Greet(<span style="color:#a31515;">"Tony"</span>);

        <span style="color:green;">// Assert
        </span><span style="color:#2b91af;">Assert</span>.That(greeting, <span style="color:#2b91af;">Is</span>.StringMatching(<span style="color:#a31515;">"Howdy Tony"</span>));
    }
}</pre>
<p>So far, this really isn’t that big of a deal.&nbsp; The client still needs to initialize the container and pass it to the instance factory.&nbsp; So what’s the advantage?&nbsp; The power of the abstraction comes to the fore when using dependency injection with frameworks such as ASP.NET MVC or WCF.&nbsp; Particularly with WCF, where you need other pieces (such as an instance provider, service behavior and service host), the abstraction afforded by the Common Instance Factory provides a uniform way to deal with different DI containers so that swapping out one for another is much easier.&nbsp; That will be the topic of my next blog post.</p>
<p>Download the Common Instance Factory from <a href="https://nuget.org/packages?q=commonintancefactory">NuGet</a>, or get the source code and samples from the <a href="http://instancefactory.codeplex.com/releases/view/88235">CodePlex</a> site.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/426/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=426&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/05/23/use-common-instance-factory-to-abstract-away-the-dependency-injection-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>
	</item>
		<item>
		<title>Roll Your Own REST-ful WCF Router</title>
		<link>http://blog.tonysneed.com/2012/04/24/roll-your-own-rest-ful-wcf-router/</link>
		<comments>http://blog.tonysneed.com/2012/04/24/roll-your-own-rest-ful-wcf-router/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 15:05:16 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=423</guid>
		<description><![CDATA[Download the code for this post here. Recently I’ve been tasked with building a WCF routing service and faced the choice of whether to go with the built-in router that ships with WCF 4.0, or to build one from scratch.&#160; &#8230; <a href="http://blog.tonysneed.com/2012/04/24/roll-your-own-rest-ful-wcf-router/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=423&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the code for this post </em><a href="http://tonysneed.com/download/router-poc.zip"><em>here</em></a><em>.</em></p>
<p>Recently I’ve been tasked with building a WCF routing service and faced the choice of whether to go with the built-in router that ships with <a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx">WCF 4.0</a>, or to build one from scratch.&nbsp; The built-in router is great for a lot of different scenarios – it provides content-based routing, multicasting, protocol bridging, and failover-based routing. However, as the MSDN documentation for the <a href="http://msdn.microsoft.com/en-us/library/ee517423.aspx">WCF Router</a> states, “<strong>The Routing Service does not currently support routing of WCF REST services.</strong>”&nbsp; The reason is fairly simple: the WCF Routing Service performs routing of messages in a way that is independent of the underlying transport, whereas a REST-based architecture is deeply rooted in the HTTP protocol and relies on the URI for delivery semantics.&nbsp; In fact, using the BasicHttpBinding with AspNetCompatibility enabled on the built-in WCF router results in a somewhat <a href="http://seroter.wordpress.com/2010/09/19/lesson-learned-wcf-routing-service-and-the-basichttpbinding/">cryptic error</a>: “Shouldn&#8217;t allocate SessionChannels if session-less and impersonating.”</p>
<p>Nevertheless, there are times when it might make sense to build a router that can talk to clients who don’t know anything about Soap, for example, an AJAX web application.&nbsp; You can also achieve a more compact data representation with plain old XML (POX) or Javascript Object Notation (JSON), which could result in greater throughput.&nbsp; While the <a href="http://msdn.microsoft.com/en-us/magazine/dd943053.aspx">ASP.NET MVC</a> or the new <a href="http://www.asp.net/web-api">ASP.NET Web API</a> might seems like attractive options, WCF is the way to go if you need to accommodate <em>both</em> Soap-based and Rest-ful clients.&nbsp; WCF offers a unified programming model with the neutral <a href="http://msdn.microsoft.com/en-us/library/ms734675.aspx">Message</a> type, which makes it easier to avoid serialization of the message body and the cost that could carry.</p>
<p>Here is the universal service contract for a routing service that can accept requests that are formatted as SOAP, POX or JSON.</p>
<pre class="code">[<span style="color:#2b91af;">ServiceContract</span>(Namespace = <span style="color:#a31515;">"urn:example:routing"</span>)]
<span style="color:blue;">public interface </span><span style="color:#2b91af;">IRoutingService
</span>{
    [<span style="color:#2b91af;">WebInvoke</span>(UriTemplate = <span style="color:#a31515;">""</span>)]
    [<span style="color:#2b91af;">OperationContract</span>(AsyncPattern = <span style="color:blue;">true</span>, Action = <span style="color:#a31515;">"*"</span>, ReplyAction = <span style="color:#a31515;">"*"</span>)]
    <span style="color:#2b91af;">IAsyncResult </span>BeginProcessRequest(<span style="color:#2b91af;">Message </span>requestMessage, <span style="color:#2b91af;">AsyncCallback </span>asyncCallback, <span style="color:blue;">object </span>asyncState);

    <span style="color:#2b91af;">Message </span>EndProcessRequest(<span style="color:#2b91af;">IAsyncResult </span>asyncResult);
}</pre>
<p>What makes this suitable for routing is that the Action and ReplyAction parameters of the OperationContract are set to “*” – allowing it to accept any request regardless of the Action.&nbsp; The contract also uses a request-response <a href="http://msdn.microsoft.com/en-us/library/aa751829.aspx">message exchange pattern</a>, which is suitable for HTTP clients that generally follow this pattern when communicating with services.</p>
<p>Another thing you’ll notice is the <a href="http://msdn.microsoft.com/en-us/library/ms734701.aspx">AsyncPattern</a> layout, with the Begin and End methods tied together by the IAsyncResult call object.&nbsp; This is a very important requirement for performance and scalability.&nbsp; WCF executes asynchronous contracts using the <a href="http://www.narendranaidu.com/2012/03/non-blocking-io-in-net-completion-ports.html">IO Completion Port Thread Pool</a>, which economizes on server resources by exchanging a 100 byte IO request packet for a 1 MB thread stack.&nbsp; This makes sense only if you initiate async IO in the Begin method.&nbsp; An Async IO operation can be things like Socket.Begin[Send|Receive], NetworkStream.Begin[Read|Write], FileStream.Begin[Read|Write] (if created asynchronously), SqlCommand.BeginExecute[Reader|NonQuery|XmlReader], or invoking a WCF service asynchronously, which is precisely what a router is designed to do.</p>
<p>Here is the implementation of the IRoutingService interface.</p>
<pre class="code">[<span style="color:#2b91af;">ServiceBehavior</span>(InstanceContextMode = <span style="color:#2b91af;">InstanceContextMode</span>.PerCall,
    AddressFilterMode = <span style="color:#2b91af;">AddressFilterMode</span>.Any, ValidateMustUnderstand = <span style="color:blue;">false</span>)]
[<span style="color:#2b91af;">AspNetCompatibilityRequirements</span>(RequirementsMode = <span style="color:#2b91af;">AspNetCompatibilityRequirementsMode</span>.Allowed)]
<span style="color:blue;">public class </span><span style="color:#2b91af;">RoutingService </span>: <span style="color:#2b91af;">IRoutingService</span>, <span style="color:#2b91af;">IDisposable
</span>{
    <span style="color:blue;">private </span><span style="color:#2b91af;">IRoutingService </span>_client;

    <span style="color:blue;">public </span><span style="color:#2b91af;">IAsyncResult </span>BeginProcessRequest(<span style="color:#2b91af;">Message </span>requestMessage, <span style="color:#2b91af;">AsyncCallback </span>asyncCallback, <span style="color:blue;">object </span>asyncState)
    {
        <span style="color:green;">// Select soap or rest client endpoint
        </span><span style="color:blue;">string </span>endpoint = <span style="color:#a31515;">"service-basic"</span>;
        <span style="color:blue;">if </span>(requestMessage.Version == <span style="color:#2b91af;">MessageVersion</span>.None)
            endpoint = <span style="color:#a31515;">"service-web"</span>;

        <span style="color:green;">// Create channel factory
        </span><span style="color:blue;">var </span>factory = <span style="color:blue;">new </span><span style="color:#2b91af;">ChannelFactory</span>&lt;<span style="color:#2b91af;">IRoutingService</span>&gt;(endpoint);

        <span style="color:green;">// Set message address
</span>        requestMessage.Headers.To = <span style="color:blue;">new </span><span style="color:#2b91af;">Uri</span>(factory.Endpoint.Address);

        <span style="color:green;">// Create client channel
        </span>_client = factory.CreateChannel();

        <span style="color:green;">// Begin request
        </span><span style="color:blue;">return</span> _client.BeginProcessRequest(requestMessage, asyncCallback, asyncState);
    }

    <span style="color:blue;">public </span><span style="color:#2b91af;">Message </span>EndProcessRequest(<span style="color:#2b91af;">IAsyncResult </span>asyncResult)
    {
        <span style="color:blue;">return </span>_client.EndProcessRequest(asyncResult);
    }

    <span style="color:blue;">public void </span>Dispose()
    {
        <span style="color:blue;">if </span>(_client != <span style="color:blue;">null</span>)
        {
            <span style="color:blue;">var </span>channel = (<span style="color:#2b91af;">IClientChannel</span>)_client;
            <span style="color:blue;">if </span>(channel.State != <span style="color:#2b91af;">CommunicationState</span>.Closed)
            {
                <span style="color:blue;">try
</span>                    channel.Close();
                <span style="color:blue;">catch
</span>                    channel.Abort();
            }
        }
    }
}</pre>
<p>First, notice that the InstanceContextMode is set to PerCall, so that an instance of the RoutingService is created upon each request.&nbsp; This allows the service to be entirely stateless and function easily in a web farm environment without maintaining client state between method calls.&nbsp; Another thing to notice is that the client proxy (IRoutingService) is declared as a member variable and shared between the Begin and End methods.</p>
<p>When I first wrote the service implementation, I noticed something strange happen when the service was invoked by a non-Soap client.&nbsp; The call to _client.BeginProcessRequest was coming right back into the service, instead of invoking the remote service, even though the factory’s endpoint address pointed to the remote service.&nbsp; What I didn’t realize at the time is that the Http transport channel will use the “To” message header when <a href="http://blogs.msdn.com/b/drnick/archive/2007/01/09/manual-addressing.aspx">manual addressing</a> is set to true, which is the case with the WebHttpBinding.&nbsp; The “To” message header is naturally pointing to the routing service, so that’s where the message is directed.&nbsp; To correct this behavior, all you need to do is manually set the “To” message header to match the factory endpoint address.</p>
<p>Probably the most important task of a router is to, well, route messages.&nbsp; But you need to decide how to instruct the router to accomplish this task.&nbsp; The trick is to do it in a way that avoids having to look at the contents of the message.&nbsp; Messages in WCF consist of two parts: headers and a body. Headers are always deserialized and buffered, whereas the body comes in as a stream.&nbsp; If you can avoid creating a message buffer and deserializing the message stream, the router will perform more efficiently.</p>
<p>For soap-based messages, the natural place for routing instructions is the header.&nbsp; Here is part of a method that reads routing instructions from the incoming message header.</p>
<pre class="code"><span style="color:blue;">public </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt; GetRoutingHeaders(<span style="color:#2b91af;">Message </span>requestMessage)
{
    <span style="color:green;">// Set routing namespace
    </span><span style="color:blue;">var </span>routingHeaders = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt;();

    <span style="color:green;">// Get soap routing headers
    </span><span style="color:blue;">if </span>(requestMessage.Version != <span style="color:#2b91af;">MessageVersion</span>.None)
    {
        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>header <span style="color:blue;">in </span>requestMessage.Headers)
        {
            <span style="color:blue;">if </span>(header.Namespace.ToLower() == _routingNamespace)
            {
                <span style="color:blue;">int </span>headerIndex = requestMessage.Headers.FindHeader
                    (header.Name, _routingNamespace);
                <span style="color:blue;">if </span>(headerIndex != -1)
                {
                    <span style="color:blue;">var </span>headerValue = requestMessage.Headers.GetHeader&lt;<span style="color:blue;">string</span>&gt;
                        (header.Name, _routingNamespace);
                    requestMessage.Headers.RemoveAt(headerIndex);
                    <span style="color:blue;">if </span>(!<span style="color:blue;">string</span>.IsNullOrWhiteSpace(headerValue))
                        routingHeaders.Add(header.Name, headerValue);
                }
            }
        }
    }</pre>
<p>For non-Soap clients using HTTP, you have basically two choices: custom HTTP headers, or you can incorporate routing instructions into the URI.&nbsp; Personally, I like the second approach better, because it makes use of the URI in a more REST-like fashion.&nbsp; Here is some code that demonstrates both these approaches.&nbsp; It first looks at the HTTP headers for routing instructions, but if there aren’t any, it then gets them from query parameters in the URI.</p>
<pre class="code"><span style="color:#2b91af;">WebHeaderCollection </span>httpHeaders = <span style="color:#2b91af;">WebOperationContext</span>.Current.IncomingRequest.Headers;
<span style="color:blue;">foreach </span>(<span style="color:blue;">string </span>headerName <span style="color:blue;">in </span>httpHeaders)
{
    <span style="color:blue;">if </span>(headerName.ToLower().StartsWith(routingNamespace))
    {
        <span style="color:blue;">string </span>name = headerName.Substring(routingNamespace.Length + 1);
        <span style="color:blue;">string </span>value = httpHeaders.Get(headerName);
        routingHeaders.Add(name, value);
    }
}
<span style="color:blue;">if </span>(routingHeaders.Count == 0)
{
    <span style="color:blue;">var </span>queryParams = <span style="color:#2b91af;">WebOperationContext</span>.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
    <span style="color:blue;">foreach </span>(<span style="color:blue;">string </span>paramKey <span style="color:blue;">in </span>queryParams.AllKeys)
    {
        <span style="color:blue;">string </span>name = paramKey.Substring(_routingNamespace.Length + 1);
        <span style="color:blue;">string </span>value = queryParams[paramKey];
        routingHeaders.Add(name, value);
    }
}</pre>
<p>Armed with routing metadata, you can look up the destination’s address in a routing table of some kind.&nbsp; This method selects GreetingService2 if the routing instructions specify the “western” region.</p>
<pre class="code"><span style="color:blue;">public string </span>GetServiceAddress(<span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">string</span>&gt; routingHeaders,
    <span style="color:blue;">string </span>defaultServiceAddress)
{
    <span style="color:green;">// Select service address based on region
    </span><span style="color:blue;">string </span>serviceAddress = defaultServiceAddress;
    <span style="color:blue;">var </span>region = (<span style="color:blue;">from </span>rh <span style="color:blue;">in </span>routingHeaders
                    <span style="color:blue;">where </span>rh.Key.ToLower() == <span style="color:#a31515;">"region"
                    </span><span style="color:blue;">select </span>rh.Value).FirstOrDefault();
    <span style="color:blue;">if </span>(region != <span style="color:blue;">null</span>)
    {
        <span style="color:blue;">if </span>(region.ToLower() == <span style="color:#a31515;">"western"</span>)
            serviceAddress = defaultServiceAddress
                .Replace(<span style="color:#a31515;">"GreetingService1"</span>, <span style="color:#a31515;">"GreetingService2"</span>);
    }
    <span style="color:blue;">return </span>serviceAddress;
}</pre>
<p>If the router isn’t going to read the message body or alter it in any way, then clients will need to send messages that can be understood by the eventual recipient of the message.&nbsp; So if both Soap and non-Soap messages will be sent to the router, the downstream services will need to expose both soap and rest endpoints.&nbsp; Furthermore, if clients are going to want to transmit messages as Json, services will need to know how to understand and respond in kind.&nbsp; For example, here is the app.config file of the GreetingService.&nbsp; The webHttp endpoint behavior allows for a Json-formatted response if the Accept or ContentType header is set to “application/json”.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">system.serviceModel</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">services</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">service </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">RoutingPrototype.Services.GreetingService1</span>"<span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">endpoint </span><span style="color:red;">address</span><span style="color:blue;">=</span>"<span style="color:blue;">Soap</span>"
                <span style="color:red;">binding</span><span style="color:blue;">=</span>"<span style="color:blue;">basicHttpBinding</span>"
                <span style="color:red;">contract</span><span style="color:blue;">=</span>"<span style="color:blue;">RoutingPrototype.Interfaces.IGreetingService</span>"
                <span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">service-basic</span>"<span style="color:blue;">/&gt;
      &lt;</span><span style="color:#a31515;">endpoint </span><span style="color:red;">address</span><span style="color:blue;">=</span>"<span style="color:blue;">Rest</span>"
                <span style="color:red;">binding</span><span style="color:blue;">=</span>"<span style="color:blue;">webHttpBinding</span>"
                <span style="color:red;">behaviorConfiguration</span><span style="color:blue;">=</span>"<span style="color:blue;">web</span>"
                <span style="color:red;">contract</span><span style="color:blue;">=</span>"<span style="color:blue;">RoutingPrototype.Interfaces.IGreetingService</span>"
                <span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">service-web</span>"<span style="color:blue;">/&gt;
      &lt;</span><span style="color:#a31515;">host</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">baseAddresses</span><span style="color:blue;">&gt;
          &lt;</span><span style="color:#a31515;">add </span><span style="color:red;">baseAddress</span><span style="color:blue;">=</span>"<span style="color:blue;">http://localhost:8000/GreetingService1</span>" <span style="color:blue;">/&gt;
        &lt;/</span><span style="color:#a31515;">baseAddresses</span><span style="color:blue;">&gt;
      &lt;/</span><span style="color:#a31515;">host</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">service</span><span style="color:blue;">&gt;
    &lt;</span><span style="color:#a31515;">behaviors</span><span style="color:blue;">&gt;
      &lt;</span><span style="color:#a31515;">endpointBehaviors</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">behavior </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">web</span>"<span style="color:blue;">&gt;
          &lt;</span><span style="color:#a31515;">webHttp </span><span style="color:red;">helpEnabled</span><span style="color:blue;">=</span>"<span style="color:blue;">true</span>"
                    <span style="color:red;">automaticFormatSelectionEnabled</span><span style="color:blue;">=</span>"<span style="color:blue;">true</span>"
                    <span style="color:red;">faultExceptionEnabled</span><span style="color:blue;">=</span>"<span style="color:blue;">true</span>"<span style="color:blue;">/&gt;
        &lt;/</span><span style="color:#a31515;">behavior</span><span style="color:blue;">&gt;
      &lt;/</span><span style="color:#a31515;">endpointBehaviors</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">behaviors</span><span style="color:blue;">&gt;
  &lt;/</span><span style="color:#a31515;">system.serviceModel</span><span style="color:blue;">&gt;</span></pre>
<p>The client-side code for sending Soap-based messages looks like this:</p>
<pre class="code"><span style="color:blue;">private static string </span>SendSoapMessage(<span style="color:blue;">string </span>name, <span style="color:blue;">string </span>addressType, <span style="color:blue;">string </span>region, <span style="color:blue;">bool </span>useFiddler)
{
    <span style="color:blue;">var </span>factory = <span style="color:blue;">new </span>ChannelFactory&lt;IGreetingService&gt;(addressType);
    <span style="color:blue;">string </span>address = factory.Endpoint.Address.ToString()
        .Replace(<span style="color:#a31515;">"localhost"</span>, ConfigurationManager.AppSettings[<span style="color:#a31515;">"MachineName"</span>]);
    <span style="color:blue;">if </span>(useFiddler) factory.Endpoint.Address = <span style="color:blue;">new </span>EndpointAddress(address);
            
    IGreetingService client = factory.CreateChannel();
    <span style="color:blue;">using </span>((<span style="color:#2b91af;">IDisposable</span>)client)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">var </span>contextScope = <span style="color:blue;">new </span>OperationContextScope((IContextChannel)client))
        {
<span style="color:green;">            </span><span style="color:blue;">if </span>(region != <span style="color:blue;">null</span>)
            {
                MessageHeader regionHeader = MessageHeader
                    .CreateHeader(<span style="color:#a31515;">"region"</span>, _routingNamespace, region);
                OperationContext.Current.OutgoingMessageHeaders.Add(regionHeader);
            }
<span style="color:green;">            </span><span style="color:blue;">return</span> client.Hello(name);
        }
    }
}
</pre>
<p>The client-side code for sending Rest-ful messages looks like this:</p>
<pre class="code"><span style="color:blue;">private static string </span>SendRestMessage(<span style="color:blue;">string </span>name, <span style="color:blue;">string </span>addressType, <span style="color:blue;">string </span>region, <span style="color:blue;">bool </span>useFiddler)
{
    <span style="color:blue;">string </span>address = ConfigurationManager.AppSettings[addressType];
    <span style="color:blue;">if </span>(useFiddler) address = address.Replace(<span style="color:#a31515;">"localhost"</span>, ConfigurationManager.AppSettings[<span style="color:#a31515;">"MachineName"</span>]);
    <span style="color:blue;">var </span>client = <span style="color:blue;">new </span>WebClient {BaseAddress = address};

    <span style="color:green;">// Set format
    </span><span style="color:blue;">string </span>format = GetFormat();
    <span style="color:blue;">if </span>(format == <span style="color:blue;">null</span>) <span style="color:blue;">return null</span>;
    <span style="color:blue;">string </span>requestString;
    <span style="color:blue;">if </span>(format == <span style="color:#a31515;">"xml"</span>)
    {
        requestString = SerializationHelper.SerializeXml(name);
        client.Headers.Add(HttpRequestHeader.ContentType, <span style="color:#a31515;">"application/xml"</span>);
    }
    <span style="color:blue;">else if </span>(format == <span style="color:#a31515;">"json"</span>)
    {
        requestString = SerializationHelper.SerializeJson(name);
        client.Headers.Add(HttpRequestHeader.ContentType, <span style="color:#a31515;">"application/json"</span>);
    }

    <span style="color:green;">// Set region header
    </span><span style="color:blue;">string </span>addressParameters = <span style="color:blue;">string</span>.Empty;
    <span style="color:blue;">if </span>(region != <span style="color:blue;">null</span>)
    {
        <span style="color:blue;">bool</span>? useHeaders = UseHttpHeaders();
        <span style="color:blue;">if </span>(useHeaders == <span style="color:blue;">null</span>) <span style="color:blue;">return null</span>;
        <span style="color:blue;">if </span>((<span style="color:blue;">bool</span>)useHeaders)
        {
            <span style="color:blue;">string </span>regionHeader = <span style="color:blue;">string</span>.Format(<span style="color:#a31515;">"</span><span style="color:#3cb371;">{0}</span><span style="color:#a31515;">:</span><span style="color:#3cb371;">{1}</span><span style="color:#a31515;">"</span>, _routingNamespace, <span style="color:#a31515;">"region"</span>);
            regionHeader = regionHeader.Replace(<span style="color:#a31515;">":"</span>, <span style="color:#a31515;">"-"</span>);
            client.Headers.Add(regionHeader, region);
        }
        <span style="color:blue;">else
        </span>{
            addressParameters = <span style="color:blue;">string</span>.Format
                (<span style="color:#a31515;">"?</span><span style="color:#3cb371;">{0}</span><span style="color:#a31515;">:region=</span><span style="color:#3cb371;">{1}</span><span style="color:#a31515;">"</span>, _routingNamespace, region);
        }
    }

    <span style="color:green;">// Send message
</span>    <span style="color:blue;">string </span>responseString = client.UploadString(addressParameters, requestString);

    <span style="color:green;">// Deserialize response
    </span><span style="color:blue;">string </span>response = <span style="color:blue;">null</span>;
    <span style="color:blue;">if </span>(format == <span style="color:#a31515;">"xml"</span>)
        response = SerializationHelper.DeserializeXml&lt;<span style="color:blue;">string</span>&gt;(responseString);
    <span style="color:blue;">else if </span>(format == <span style="color:#a31515;">"json"</span>)
        response = SerializationHelper.DeserializeJson&lt;<span style="color:blue;">string</span>&gt;(responseString);
    <span style="color:blue;">return </span>response;
}</pre>
<p>If you look at the message received by the either the router or the downstream service, you won’t see a hint of Json, even when the message sent by the client is clearly Json.&nbsp; (<a href="http://blog.tonysneed.com/2012/04/08/ninject-wcf-extensions-for-restful-services/">SerializationHelper</a> is a class I wrote to serialize Xml and Json using WCF’s data contract serializer.)&nbsp; The reason is that the translation from and to Json is performed by the webHttp endpoint behavior. If you want to see what is actually sent across the wire, you’ll need to employ an HTTP sniffer such as <a href="http://www.fiddler2.com/fiddler2/">Fiddler</a>.&nbsp; However, <a href="http://fiddler2.com/Fiddler/help/hookup.asp#Q-DOTNET">configuring</a> it for use with <a href="http://www.west-wind.com/weblog/posts/2009/Jan/14/Monitoring-HTTP-Output-with-Fiddler-in-NET-HTTP-Clients-and-WCF-Proxies">.NET clients</a> can be a joy (sarcasm intended).&nbsp; The easiest approach I found was to substitute “localhost” in client endpoint addresses with the actual machine name, which you can store as a setting in app.config.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="fiddler-json" border="0" alt="fiddler-json" src="http://tonysneed.files.wordpress.com/2012/04/fiddler-json.jpg?w=607&h=359" width="607" height="359"></p>
<p>Here you can see an HTTP POST message transmitted with a custom routing header, urn-example-routing-region, with a value of “western”.&nbsp; Both the request and response are formatted as a simple Json string.</p>
<p>WCF will give you all the tools you need to write a scalable, high-performance router with a minimal amount of code.&nbsp; Making it play nice with Rest, however, requires some effort, as well as familiarity with how WCF deals with Rest-based messages under the covers.&nbsp; Here are some resources I found helpful in getting my head around WCF addressing and message-handling and the mechanics of building a WCF routing service:</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc163412.aspx">WCF Addressing In Depth (MSDN Magazine June 2007)</a><br /><a href="http://msdn.microsoft.com/en-us/magazine/cc163447.aspx#S3">WCF Messaging Fundamentals (MSDN Magazine April 2007)</a><br /><a href="http://msdn.microsoft.com/en-us/magazine/cc500646.aspx">Building a WCF Router, Part 1 (MSDN Magazine April 2008)</a><br /><a href="http://msdn.microsoft.com/en-us/magazine/cc546553.aspx">Building a WCF Router, Part 2 (MSDN Magazine June 2008)</a></p>
<p><em>You can download the code for this post </em><a href="http://tonysneed.com/download/router-poc.zip"><em>here</em></a><em>. </em>Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/423/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/423/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/423/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=423&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/04/24/roll-your-own-rest-ful-wcf-router/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/04/fiddler-json.jpg" medium="image">
			<media:title type="html">fiddler-json</media:title>
		</media:content>
	</item>
		<item>
		<title>Ninject WCF Extensions for RESTful Services</title>
		<link>http://blog.tonysneed.com/2012/04/08/ninject-wcf-extensions-for-restful-services/</link>
		<comments>http://blog.tonysneed.com/2012/04/08/ninject-wcf-extensions-for-restful-services/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 14:53:58 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=415</guid>
		<description><![CDATA[Download the code for this post. A while ago I blogged about using Ninject for dependency injection with WCF Services.&#160; The advantage of using DI is that it allows you to achieve loose coupling in your application architecture, so that &#8230; <a href="http://blog.tonysneed.com/2012/04/08/ninject-wcf-extensions-for-restful-services/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=415&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Download the <a href="http://tonysneed.com/download/ninject-wcf-rest.zip">code</a> for this post.</em></p>
<p>A while ago I <a href="http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/">blogged</a> about using Ninject for <a href="http://msdn.microsoft.com/en-us/magazine/cc163739.aspx">dependency injection</a> with WCF Services.&nbsp; The <a href="http://blog.ploeh.dk/">advantage</a> of using DI is that it allows you to achieve <a href="http://blog.tonysneed.com/2011/10/08/peeling-back-the-onion-architecture/">loose coupling</a> in your application architecture, so that you’re not tightly bound to a particular infrastructure implementation, such as data access or logging.&nbsp; The problem with WCF services is that by default they are required to have a parameterless constructor, which does not play nice with DI containers, such as <a href="http://www.ninject.org/">Ninject</a>, which support injection of dependencies via constructor parameters.</p>
<p><a href="https://github.com/ninject/ninject.extensions.wcf/wiki"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ninject-wcf-update" border="0" alt="ninject-wcf-update" src="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-update.jpg?w=587&h=352" width="587" height="352"></a></p>
<p>I had the need recently to set up a REST-style WCF Services project and wanted to use Ninject for DI with it. Luckily, the <a href="https://github.com/ninject/ninject.extensions.wcf/wiki">Ninject WCF Extension</a> project had been updated to support REST, so I updated the <a href="https://nuget.org/">Nuget</a> package and discovered the project would not compile.&nbsp; I found out that the static KernelContainer class had been deprecated, so I had to refactor my code to remove references to it.&nbsp; I also noticed there was no longer any need to derive the Global.asax code file from NinjectWcfApplication, because the extension now uses WebActivator to configure Ninject on application startup.&nbsp; A NinjectWebCommon.cs file is placed in an App_Start folder. There you simply add code to a RegisterServices method in order to load your Ninject modules and perform the bindings. (When updating the NuGet package on the other projects, I had to manually remove the App_Start folder.)</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ninject-wcf-app-start" border="0" alt="ninject-wcf-app-start" src="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-app-start.jpg?w=297&h=217" width="297" height="217"></p>
<p>Typically when exposing a REST-type endpoint from a WCF service, you would leverage the ASP.NET UrlRoutingModule by adding a ServiceRoute to the RouteTable in the Application_Start method of your Global.asax.cs file.&nbsp; Things get a little tricky, however, if you want to expose both SOAP and REST endpoints from the same WCF service.&nbsp; In this case, you’ll want to supply a ServiceHostFactory-derived class when registering the service route, which let’s you specify an endpoint address that is different than the base HTTP address used for the SOAP endpoint.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">RestServiceHostFactory</span>&lt;TServiceContract&gt; : <span style="color:#2b91af;">NinjectWebServiceHostFactory
</span>{
    <span style="color:blue;">protected override </span><span style="color:#2b91af;">ServiceHost </span>CreateServiceHost(<span style="color:#2b91af;">Type </span>serviceType, <span style="color:#2b91af;">Uri</span>[] baseAddresses)
    {
        <span style="color:#2b91af;">ServiceHost </span>host = <span style="color:blue;">base</span>.CreateServiceHost(serviceType, baseAddresses);
        <span style="color:blue;">var </span>webBehavior = <span style="color:blue;">new </span><span style="color:#2b91af;">WebHttpBehavior
        </span>{
            AutomaticFormatSelectionEnabled = <span style="color:blue;">true</span>,
            HelpEnabled = <span style="color:blue;">true</span>,
            FaultExceptionEnabled = <span style="color:blue;">true
        </span>};
        <span style="color:blue;">var </span>endpoint = host.AddServiceEndpoint(<span style="color:blue;">typeof</span>(TServiceContract), <span style="color:blue;">new </span><span style="color:#2b91af;">WebHttpBinding</span>(), <span style="color:#a31515;">"Rest"</span>);
        endpoint.Name = <span style="color:#a31515;">"rest"</span>;
        endpoint.Behaviors.Add(webBehavior);
        <span style="color:blue;">return </span>host;
    }
}</pre>
<p>Here is code from Global.asax.cs which references RestServiceHostFactory:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Global </span>: <span style="color:#2b91af;">HttpApplication
</span>{
    <span style="color:blue;">protected void </span>Application_Start(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">EventArgs </span>e)
    {
        RegisterRoutes();
    }

    <span style="color:blue;">private void </span>RegisterRoutes()
    {
        <span style="color:green;">// Add rest service route
        </span><span style="color:#2b91af;">RouteTable</span>.Routes.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">ServiceRoute</span>(<span style="color:#a31515;">"GreetingService"</span>,
            <span style="color:blue;">new </span><span style="color:#2b91af;">RestServiceHostFactory</span>&lt;<span style="color:#2b91af;">IGreetingService</span>&gt;(), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">GreetingService</span>)));
    }
}</pre>
<p>Browsing to the REST-endpoint, and appending <a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx">/help</a> to the url, displays a list of available operations.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="ninject-wcf-rest" border="0" alt="ninject-wcf-rest" src="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-rest.jpg?w=625&h=201" width="625" height="201"></a></p>
<p>In my <a href="http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/">original blog post</a> on this topic I introduced a NinjectServiceHelper class that can be used by test classes to spin up matching services and clients on the fly.&nbsp; I refactored this class to support REST scenarios by adding the required endpoint behavior for the WebHttpBinding.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">NinjectServiceHelper</span>&lt;TServiceContract, TServiceType&gt; : <span style="color:#2b91af;">IDisposable
</span>{
    <span style="color:blue;">bool </span>_disposed;

    <span style="color:blue;">public </span>NinjectServiceHelper(<span style="color:#2b91af;">IServiceBehavior </span>serviceBehavior, <span style="color:blue;">string </span>address, <span style="color:#2b91af;">Binding </span>binding)
    {
        <span style="color:green;">// Create Ninject service host
        </span>_serviceHost = <span style="color:blue;">new </span><span style="color:#2b91af;">NinjectServiceHost</span>(serviceBehavior, <span style="color:blue;">typeof</span>(TServiceType));

        <span style="color:green;">// Add endpoint
        </span>_serviceHost.AddServiceEndpoint(<span style="color:blue;">typeof</span>(TServiceContract), binding, address);

        <span style="color:green;">// Add web behavior
        </span><span style="color:blue;">if </span>(binding.GetType() == <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">WebHttpBinding</span>))
        {
            <span style="color:blue;">var </span>webBehavior = <span style="color:blue;">new </span><span style="color:#2b91af;">WebHttpBehavior
            </span>{
                AutomaticFormatSelectionEnabled = <span style="color:blue;">true</span>,
                HelpEnabled = <span style="color:blue;">true</span>,
                FaultExceptionEnabled = <span style="color:blue;">true
            </span>};
            _serviceHost.Description.Endpoints[0].Behaviors.Add(webBehavior);
        }

        <span style="color:green;">// Add service metadata
        </span><span style="color:blue;">var </span>metadataBehavior = <span style="color:blue;">new </span><span style="color:#2b91af;">ServiceMetadataBehavior</span>();
        <span style="color:blue;">if </span>(binding.GetType() == <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">BasicHttpBinding</span>))
        {
            metadataBehavior.HttpGetEnabled = <span style="color:blue;">true</span>;
            metadataBehavior.HttpGetUrl = <span style="color:blue;">new </span><span style="color:#2b91af;">Uri</span>(address);
        }
        _serviceHost.Description.Behaviors.Add(metadataBehavior);

        <span style="color:green;">// Open service host
        </span>_serviceHost.Open();

        <span style="color:green;">// Init client
        </span><span style="color:blue;">var </span>factory = <span style="color:blue;">new </span><span style="color:#2b91af;">ChannelFactory</span>&lt;TServiceContract&gt;(binding);
        _client = factory.CreateChannel(<span style="color:blue;">new </span><span style="color:#2b91af;">EndpointAddress</span>(address));
    }

    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ServiceHost </span>_serviceHost;
    <span style="color:blue;">public </span><span style="color:#2b91af;">ServiceHost </span>ServiceHost
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">if </span>(_disposed)
                <span style="color:blue;">throw new </span><span style="color:#2b91af;">ObjectDisposedException</span>(<span style="color:#a31515;">"NinjectServiceHelper"</span>);
            <span style="color:blue;">return </span>_serviceHost;
        }
    }

    <span style="color:blue;">private readonly </span>TServiceContract _client;
    <span style="color:blue;">public </span>TServiceContract Client
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">if </span>(_disposed)
                <span style="color:blue;">throw new </span><span style="color:#2b91af;">ObjectDisposedException</span>(<span style="color:#a31515;">"NinjectServiceHelper"</span>);
            <span style="color:blue;">return </span>_client;
        }
    }

    <span style="color:blue;">public void </span>Dispose()
    {
        <span style="color:blue;">if </span>(!_disposed)
        {
            ((<span style="color:#2b91af;">IDisposable</span>)_serviceHost).Dispose();
            ((<span style="color:#2b91af;">IDisposable</span>)_client).Dispose();
            _disposed = <span style="color:blue;">true</span>;
        }
    }
}</pre>
<p>The test class then loads a Ninject module in the TestFixtureSetup method that adds named bindings to the kernel for SOAP and REST WCF endpoints.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">ServicesModule </span>: <span style="color:#2b91af;">NinjectModule
</span>{
    <span style="color:blue;">public override void </span>Load()
    {
        <span style="color:green;">// Basic service host
        </span>Kernel.Bind&lt;<span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;&gt;()
            .ToSelf()
            .Named(<span style="color:#a31515;">"Basic"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"address"</span>, <span style="color:#a31515;">"http://localhost:1234/GreetingService/Soap/"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"binding"</span>, <span style="color:blue;">new </span><span style="color:#2b91af;">BasicHttpBinding</span>());

        <span style="color:green;">// Tcp service host
        </span>Kernel.Bind&lt;<span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;&gt;()
            .ToSelf()
            .Named(<span style="color:#a31515;">"Tcp"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"address"</span>, <span style="color:#a31515;">"net.tcp://localhost:9999/GreetingService/Tcp/"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"binding"</span>, <span style="color:blue;">new </span><span style="color:#2b91af;">NetTcpBinding</span>());

        <span style="color:green;">// Rest service host
        </span>Kernel.Bind&lt;<span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;&gt;()
            .ToSelf()
            .Named(<span style="color:#a31515;">"Rest"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"address"</span>, <span style="color:#a31515;">"http://localhost:1234/GreetingService/Rest/"</span>)
            .WithConstructorArgument(<span style="color:#a31515;">"binding"</span>, <span style="color:blue;">new </span><span style="color:#2b91af;">WebHttpBinding</span>());
    }
}</pre>
<p>The test methods then obtain the appropriate helper instance by name.</p>
<pre class="code"><span style="color:blue;">private void </span>Greeting_Soap(<span style="color:blue;">string </span>protocol)
{
    <span style="color:green;">// Arrange
    </span><span style="color:blue;">using </span>(<span style="color:blue;">var </span>helper = _kernel.Get&lt;<span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;&gt;(protocol))
    {
        <span style="color:blue;">using </span>((<span style="color:#2b91af;">IDisposable</span>)helper.Client)
        {
            <span style="color:green;">// Act
            </span><span style="color:blue;">string </span>greeting = helper.Client.Hello();

            <span style="color:green;">// Assert
            </span><span style="color:#2b91af;">Assert</span>.That(greeting, <span style="color:#2b91af;">Is</span>.StringMatching(<span style="color:#a31515;">"Hello"</span>));
        }
    }
}

<span style="color:blue;">private void </span>Greeting_Rest(<span style="color:blue;">string </span>format)
{
    <span style="color:blue;">using </span>(<span style="color:blue;">var </span>helper = _kernel.Get&lt;<span style="color:#2b91af;">NinjectServiceHelper</span>&lt;<span style="color:#2b91af;">IGreetingService</span>, <span style="color:#2b91af;">GreetingService</span>&gt;&gt;(<span style="color:#a31515;">"Rest"</span>))
    {
        <span style="color:green;">// Arrange
        </span><span style="color:blue;">var </span>client = <span style="color:blue;">new </span><span style="color:#2b91af;">WebClient</span>();
        <span style="color:blue;">if </span>(format == <span style="color:#a31515;">"Json"</span>)
            client.Headers.Add(<span style="color:#2b91af;">HttpRequestHeader</span>.Accept, <span style="color:#a31515;">"application/" </span>+ format);
        client.BaseAddress = helper.ServiceHost.Description.Endpoints[0].Address.ToString();

        <span style="color:green;">// Act
        </span><span style="color:blue;">string </span>result = client.DownloadString(<span style="color:#a31515;">"Hello"</span>);
        <span style="color:blue;">string </span>greeting;
        <span style="color:blue;">if </span>(format == <span style="color:#a31515;">"Xml"</span>)
            greeting = <span style="color:#2b91af;">SerializationHelper</span>.DeserializeXml&lt;<span style="color:blue;">string</span>&gt;(result);
        <span style="color:blue;">else if </span>(format == <span style="color:#a31515;">"Json"</span>)
            greeting = <span style="color:#2b91af;">SerializationHelper</span>.DeserializeJson&lt;<span style="color:blue;">string</span>&gt;(result);
        <span style="color:blue;">else
            throw new </span><span style="color:#2b91af;">Exception</span>(<span style="color:#a31515;">"Format not supported: " </span>+ format);

        <span style="color:green;">// Assert
        </span><span style="color:#2b91af;">Assert</span>.That(greeting, <span style="color:#2b91af;">Is</span>.StringMatching(<span style="color:#a31515;">"Hello"</span>));
    }
}</pre>
<p>My SerializationHelper class simplifies the task of converting Xml and Json to and from CLR objects.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">SerializationHelper
</span>{
    <span style="color:blue;">public static string </span>SerializeXml&lt;T&gt;(T obj)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">var </span>ms = <span style="color:blue;">new </span><span style="color:#2b91af;">MemoryStream</span>())
        {
            <span style="color:blue;">var </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractSerializer</span>(<span style="color:blue;">typeof</span>(T));
            serializer.WriteObject(ms, obj);
            <span style="color:blue;">string </span>retVal = <span style="color:#2b91af;">Encoding</span>.Default.GetString(ms.ToArray());
            <span style="color:blue;">return </span>retVal;
        }
    }

    <span style="color:blue;">public static </span>T DeserializeXml&lt;T&gt;(<span style="color:blue;">string </span>xml)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">var </span>reader = <span style="color:blue;">new </span><span style="color:#2b91af;">StringReader</span>(xml))
        {
            <span style="color:blue;">using </span>(<span style="color:blue;">var </span>xmlReader = <span style="color:#2b91af;">XmlReader</span>.Create(reader))
            {
                <span style="color:blue;">var </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractSerializer</span>(<span style="color:blue;">typeof</span>(T));
                <span style="color:blue;">var </span>obj = (T)serializer.ReadObject(xmlReader);
                <span style="color:blue;">return </span>obj;
            }
        }
    }

    <span style="color:blue;">public static string </span>SerializeJson&lt;T&gt;(T obj)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">var </span>ms = <span style="color:blue;">new </span><span style="color:#2b91af;">MemoryStream</span>())
        {
            <span style="color:blue;">var </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractJsonSerializer</span>(<span style="color:blue;">typeof</span>(T));
            serializer.WriteObject(ms, obj);
            <span style="color:blue;">string </span>retVal = <span style="color:#2b91af;">Encoding</span>.Default.GetString(ms.ToArray());
            <span style="color:blue;">return </span>retVal; 
        }
    }

    <span style="color:blue;">public static </span>T DeserializeJson&lt;T&gt;(<span style="color:blue;">string </span>json)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">var </span>ms = <span style="color:blue;">new </span><span style="color:#2b91af;">MemoryStream</span>(<span style="color:#2b91af;">Encoding</span>.Unicode.GetBytes(json)))
        {
            <span style="color:blue;">var </span>serializer = <span style="color:blue;">new </span><span style="color:#2b91af;">DataContractJsonSerializer</span>(<span style="color:blue;">typeof</span>(T));
            <span style="color:blue;">var </span>obj = (T)serializer.ReadObject(ms);
            <span style="color:blue;">return </span>obj; 
        }
    }
}</pre>
<p>Ninject’s WCF extension makes it easy to build both SOAP and REST style WCF services that use dependency injection for apps that are loosely coupled to specific infrastructure implementations.&nbsp; The project <a href="https://github.com/ninject/ninject.extensions.wcf/tree/master/src/Examples">examples</a> up on GitHub also demonstrate self-hosting scenarios.</p>
<p>Download the code for this blog post <a href="http://tonysneed.com/download/ninject-wcf-rest.zip">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/415/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=415&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/04/08/ninject-wcf-extensions-for-restful-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-update.jpg" medium="image">
			<media:title type="html">ninject-wcf-update</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-app-start.jpg" medium="image">
			<media:title type="html">ninject-wcf-app-start</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/04/ninject-wcf-rest.jpg" medium="image">
			<media:title type="html">ninject-wcf-rest</media:title>
		</media:content>
	</item>
		<item>
		<title>SSD + SATA = Best of Both Worlds</title>
		<link>http://blog.tonysneed.com/2012/04/02/ssd-sata-best-of-both-worlds/</link>
		<comments>http://blog.tonysneed.com/2012/04/02/ssd-sata-best-of-both-worlds/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 14:00:07 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[Apple]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=410</guid>
		<description><![CDATA[Every once and a while I pull something off that makes me smile.&#160; I experienced this sensation last week when I swapped out the DVD drive in my MacBook Pro and replaced it with the 500 GB SATA hard drive &#8230; <a href="http://blog.tonysneed.com/2012/04/02/ssd-sata-best-of-both-worlds/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=410&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Every once and a while I pull something off that makes me smile.&nbsp; I experienced this sensation last week when I swapped out the DVD drive in my MacBook Pro and replaced it with the 500 GB <a href="http://en.wikipedia.org/wiki/SATA">SATA</a> hard drive that came with the machine.&nbsp; When I first got the laptop, I purchased a lightening-fast <a href="http://www.amazon.com/Vertex-120GB-VTX3-25SAT3-120G-Solid-State/dp/B004Q81CKY/ref=pd_cp_pc_0">240 GB</a> <a href="http://en.wikipedia.org/wiki/Ssd">SSD</a> hard drive to replace the 500 GB drive, and I put the original drive in a case to use it for Time Machine backups.&nbsp; While I enjoyed the improved speed of the solid state drive, I soon ran out of space.&nbsp; I used <a href="http://www.derlien.com/">Disk Inventory X</a> to try and figure out where all the space went and was able to free up some of it, but I also run a Windows 7 virtual machine using <a href="http://www.parallels.com/products/desktop/">Parallels Desktop</a>, which takes up about 70 GB, and the rest of the space was taken up by stuff I wanted to keep or was difficult to extricate.&nbsp; The 240 GB SSD cost me about $300 on Amazon, but upgrading to 480 GB would have run me close to $800 – too painful.&nbsp; Besides, a lot of space is for things like videos and audio that don’t need the blinding speed of SSD, which I wanted to reserve for the stuff I use all the time, like the main OS, programs, documents, and my Windows VM.</p>
<p><a href="http://store.mcetech.com/Merchant2/merchant.mvc?Screen=PROD&amp;Product_Code=OBSXGB-UNB&amp;Category_Code=STORHDOPTIBAY&amp;Product_Count=0"><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="mce-drive" border="0" alt="mce-drive" src="http://tonysneed.files.wordpress.com/2012/04/mce-drive.jpg?w=320&h=373" width="320" height="373"></a></p>
<p>The natural solution was to purchase use a more economical SATA drive as a supplemental storage device, but I dreaded the idea of having to plug one into the USB port whenever I wanted to access some media.&nbsp; Then I ran across an <a href="http://www.markc.me.uk/MarkC/Blog/Entries/2009/9/1_Second_Hard_Disk_into_a_Macbook_Pro_Unibody.html">article</a> describing how to install a second hard drive into a MacBook Pro by removing the optical DVD drive and placing it in a separate enclosure.&nbsp; This made perfect sense to me, since I hardly ever play CD’s or DVD’s using my computer.&nbsp; So I went ahead and purchased the <a href="http://store.mcetech.com/Merchant2/merchant.mvc?Screen=PROD&amp;Product_Code=OBSXGB-UNB&amp;Category_Code=STORHDOPTIBAY&amp;Product_Count=0">kit</a> for about $100 and set about performing the operation.&nbsp; However, the instructions that came with it did not cover my model (early 2011) and were too high level for me to feel confident about.&nbsp; Thankfully, the support folks for the kit sent me a link to a very good set of <a href="http://www.ifixit.com/Guide/Installing-MacBook-Pro-13-Inch-Unibody-Early-2011-Optical-Drive-Replacement/5122/1">instructions</a> for removing the optical drive.&nbsp; It was tricky (especially when it came to putting all the screws back in the right way), but I managed to pull it off.&nbsp; I took out the DVD drive, placed it in the enclosure that came with the kit, then inserted the 500 GB SATA that came with the machine, and voila! I had a total 740 GB of storage internal to my laptop.</p>
<p>The next step was to free up space on the SDD by moving files over to the SATA.&nbsp; That’s where Disk Inventory X came in handy, helping me identity the largest files.&nbsp; However, what I really wanted to do was configure iTunes to use the SATA for its media location.&nbsp; I found useful <a href="http://www.mactalk.com.au/18/97127-moving-itunes-backup-folder-useful-ssd-users.html">information</a> on how to do that.&nbsp; While I was at I, I moved <a href="http://support.apple.com/kb/HT1229?viewlocale=en_US">iPhoto</a>, <a href="http://www.smaier.net/blog/how-tos/change-location-mobilesync-folder-mac">MobileSync</a>, and even my <a href="http://www.ehow.com/how_2269704_apple-mail-settings-email-mac.html">Mail</a> folders.&nbsp; I kept my applications, Windows VM and most of my documents on the SSD to take advantage of faster access speed, but placed the other stuff on the SATA, as well as space-hogging video files.&nbsp; I am quite satisfied with the result, and I haven’t seen problems with heat or battery drain.</p>
<p>The main reason I jettisoned my PC in favor of a Mac was pure and simple: better hardware.&nbsp; With my Dell laptop, I had to lug around this huge brick for the power supply, which had to be replaced every 6 months. I also had to buy a fan to keep it cool, and the battery life was less than 2 hours. With the Mac, I don’t need an extra fan, and the power supply is a light little square with a small magnetic connector.&nbsp; And I get several hours battery life – even when running Windows.&nbsp; I do use Mac OS X Lion for things like contacts, calendar and mail, but with <a href="http://www.apple.com/icloud/">iCloud</a> everything is automatically synced across all my other devices.&nbsp; You guessed it: my iPhone and iPad.&nbsp; There are a lot of also-rans in the phone and tablet spaces, but when it comes to consumer bliss, there’s a lot to be said for the vision <a href="http://itunes.apple.com/us/book/steve-jobs/id431617578?mt=11">Steve Jobs</a> had for software-hardware integration.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/410/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/410/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/410/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=410&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/04/02/ssd-sata-best-of-both-worlds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/04/mce-drive.jpg" medium="image">
			<media:title type="html">mce-drive</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple MVVM Toolkit for Silverlight 5.0, Windows Phone 7.1</title>
		<link>http://blog.tonysneed.com/2012/03/02/simple-mvvm-toolkit-for-silverlight-5-0-windows-phone-7-1/</link>
		<comments>http://blog.tonysneed.com/2012/03/02/simple-mvvm-toolkit-for-silverlight-5-0-windows-phone-7-1/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 17:08:00 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=403</guid>
		<description><![CDATA[I’ve just upgraded my Simple MVVM Toolkit to support Silverlight 5.0 and Windows Phone 7.1!  You can download the latest version here and take it for a spin – or get it from the Visual Studio Extensions Gallery by opening &#8230; <a href="http://blog.tonysneed.com/2012/03/02/simple-mvvm-toolkit-for-silverlight-5-0-windows-phone-7-1/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=403&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’ve just upgraded my <a href="http://simplemvvmtoolkit.codeplex.com/">Simple MVVM Toolki</a>t to support <a href="http://www.silverlight.net/learn/overview/what's-new-in-silverlight-5">Silverlight 5.0</a> and <a href="http://msdn.microsoft.com/en-us/library/ff402535(v=vs.92).aspx">Windows Phone 7.1</a>!  You can download the latest version <a href="http://simplemvvmtoolkit.codeplex.com/releases/view/83316">here</a> and take it for a spin – or get it from the <a href="http://visualstudiogallery.msdn.microsoft.com/74b7d72b-360a-4b5d-a634-01bc970487a4">Visual Studio Extensions Gallery</a> by opening Visual Studio and selecting <strong>Extensions Manager</strong> from the Tools menu. Before you run the installer, however, you should install the <a href="http://simplemvvmtoolkit.codeplex.com/wikipage?title=Prerequisites">prerequisites</a>, which now include <a href="http://www.microsoft.com/download/en/details.aspx?id=28358">Silverlight 5 Tools</a> and <a href="http://silverlight.codeplex.com/releases/view/78435">Toolkit</a>, <a href="http://www.microsoft.com/download/en/confirmation.aspx?id=9503">Expression Blend Preview for Silverlight 5</a> (this will be replaced by the Blend 5 SDK when it comes out), and the <a href="http://www.microsoft.com/download/en/details.aspx?id=27570">Windows Phone SDK 7.1</a>.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="sl4-5" src="http://tonysneed.files.wordpress.com/2012/03/sl4-5.png?w=614&h=430" alt="sl4-5" width="614" height="430" border="0" /></p>
<p>You can still use the toolkit to develop MVVM apps for Silverlight 4 if you wish, and the Visual Studio <strong>project templates</strong> include versions for <em>both Silverlight versions – 4 and 5</em>.  The project templates for a plain vanilla Silverlight apps, as well as Silverlight apps using WCF RIA Services, allow you to choose which version of Silverlight you want to use.  You still get all the source code, supporting libraries, and an abundance of samples.  If you have questions or comments, feel free to post them on the project <a href="http://simplemvvmtoolkit.codeplex.com/discussions">discussion board</a>.  And if you’re getting up to speed on MVVM with the toolkit, be sure to check out the <a href="http://blog.tonysneed.com/2011/04/18/getting-started-screencast-for-simple-mvvm-toolkit/">Getting Started screencast</a>.  Then when you’re ready, watch the <a href="http://blog.tonysneed.com/2011/04/28/screencast-real-world-mvvm-with-wcf-ria-services/">Real-World screencasts</a>.</p>
<p>I’ve also updated the <a href="http://nuget.org/">NuGet</a> packages for Simple MVVM Toolkit.  To get those, install the NuGet package manager from the Extensions Manager command under the Tools menu, then search for “SimpleMvvm” and select a package to install, depending on the type of project you have: WPF, Windows Phone, Silverlight 4 or Silverlight 5.  I preserved the existing Silverlight package for SL4, but I added a new package, <a href="https://nuget.org/packages/SimpleMvvmToolkit.Silverlight5">Silverlight5</a>, for SL5.  The packages used to include the entire installer but now only contain the binaries and a readme text file.  While I encourage most folks to run the installer to get the code snippets and Visual Studio templates, there are cases where all you want is the toolkit DLL and its supporting assemblies.  In that case, installing the NuGet package would be your preferred route.  Otherwise, run the <a href="http://simplemvvmtoolkit.codeplex.com/releases/view/83316">full installer</a> from the CodePlex site and you’ll get the entire Simple MVVM Toolkit experience.</p>
<p>Enjoy!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/403/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=403&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/03/02/simple-mvvm-toolkit-for-silverlight-5-0-windows-phone-7-1/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/03/sl4-5.png" medium="image">
			<media:title type="html">sl4-5</media:title>
		</media:content>
	</item>
		<item>
		<title>Screening C# Candidates: Let&#8217;s Play 20 Questions!</title>
		<link>http://blog.tonysneed.com/2012/02/28/screening-c-candidates-lets-play-20-questions/</link>
		<comments>http://blog.tonysneed.com/2012/02/28/screening-c-candidates-lets-play-20-questions/#comments</comments>
		<pubDate>Tue, 28 Feb 2012 17:56:23 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=400</guid>
		<description><![CDATA[Over the past year I was involved in the process of interviewing candidates for both mid and senior level developer positions.&#160; We would bring them in for a face-to-face interview, sometimes with multiple interviewers, only to find out they were &#8230; <a href="http://blog.tonysneed.com/2012/02/28/screening-c-candidates-lets-play-20-questions/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=400&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Over the past year I was involved in the process of interviewing candidates for both mid and senior level developer positions.&nbsp; We would bring them in for a face-to-face interview, sometimes with multiple interviewers, only to find out they were unable to answer the most basic technical questions concerning C# and .NET.&nbsp; I’m of the persuasion that every .NET developer should understand basic concepts, such as C# language syntax, inheritance, generics, memory management, threading, etc. Without such an understanding, a developer can end up writing apps that are shot-through with problems that make the code difficult to debug and maintain.</p>
<p>Furthermore, I’m looking for a developer with a <em>thirst for knowledge</em>.&nbsp; The technical landscape is constantly shifting, and developers need to come up to speed quickly if they are going to be able to leverage latest enhancements to the platform.&nbsp; In addition, the breadth of the technical spectrum is mind-boggling, and a developer needs the capacity to absorb vast quantities of knowledge from various parts of the framework.&nbsp; For example, someone might be called upon to build a WPF app retrieving data from a WCF service that queries a SQL database using Entity Framework with Ninject for dependency injection and MOQ for unit testing.&nbsp; If a developer has a grasp of the fundamentals of C# and .NET, it tells me they are motivated to dig deeper to understand how things work under the covers, and take the time to acquire technical expertise both through reading and hands-on coding.</p>
<p>In a face-to-face interview, I can take time to ask probing questions and get a fairly good feel for a candidate’s technical prowess.&nbsp; However, there needs to be a process to screen out candidates who lack even the most basic understanding of .NET fundamentals.&nbsp; This is the purpose of the <em>technical phone screen</em>.&nbsp; It should take no more than 15 minutes to conduct, and ideally it can be administered by a non-technical person, such as a project manager or technical recruiter.&nbsp; For this purpose I have composed a list of <a href="http://en.wikipedia.org/wiki/Twenty_Questions">20 Questions</a>, each of which has a one or two word answer.&nbsp; Here is the list of questions without answers, which you can use to quiz yourself (see the end of the post for the answers).</p>
<p><strong>C# Phone Screen Questions (without Answers)</strong></p>
<p>1. What kind of type is a string?<br />2. What kind of type is a double?<br />3. What keyword defines a custom value type?<br />4. Can a class have more than one direct base class?<br />5. What keyword makes a member visible to inherited classes?<br />6. What keyword makes a class visible only within its assembly?<br />7. What keyword allows a method to be overridden?<br />8. What keyword requires a method to be overridden?<br />9. What keyword prevents a class from being used as a base class?<br />10. What keyword returns true if a cast will succeed?<br />11. What keyword returns null if a cast will not succeed?<br />12. What keyword ensures code execution even if an exception occurs?<br />13. What keyword calls IDisposable.Dispose?<br />14. What keyword constrains a generic type argument to derive from a particular class?<br />15. What two keywords used together return IEnumerable&lt;T&gt;?<br />16. What keyword would you use to define an inline variable in a LINQ query?<br />17. What keyword brings an extension method into scope?<br />18. What keyword do you add to a delegate to force subscribers to use += or –=?<br />19. What method do you call on a delegate to run it on a background thread?<br />20. What keyword provides thread synchronization?</p>
<p>The nice thing about this approach is that is should not take just a few minutes to administer, it can be given by anyone regardless of technical background, and the answers are fairly cut and dried.&nbsp; Of course, the questions are not meant to be exhaustive and are only scratching the surface of CLR and C# fundamentals.&nbsp; Just because someone can answer them does not mean they have a firm grasp of the .NET type system, garbage collection mechanics, JIT compilation issues, or multi-threading synchronization techniques.&nbsp; Neither do the questions touch on any of the “pillars” of the .NET Framework API, such as data access (Entity Framework), web services (WCF), or presentation platforms (WPF, SL, ASP.NET MVC).&nbsp; Nor do they attempt to ascertain logical or critical thinking ability. The only way to test for those things is to perform an in-depth technical interview performed by a senior technical specialist.&nbsp; This is not to say that a mid-level developer will know all there is to know. What you are really looking for is not raw knowledge per se, but the capacity to absorb and integrate technical knowledge and the desire to know how things work.&nbsp; If a person has ever bothered to read a book or technical article or taken a training course, their answers will set them apart from the crowd of folks who don’t make time for ongoing professional development.</p>
<p>If you’re reading this blog post and want to know where to begin, my first suggestion would be to run, not walk, to nearest bookseller or online bookstore and pick up <a href="http://www.amazon.com/CLR-via-C-Jeffrey-Richter/dp/0735627045/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1330442848&amp;sr=1-1">Jeffrey Richter’s CLR via C#</a>, which is presently in its third edition.&nbsp; My short list for the books on various .NET API’s is <a href="http://www.amazon.com/Programming-Entity-Framework-Building-Centric/dp/0596807260/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1330443798&amp;sr=1-1">Programming Entity Framework by Julie Lerman</a>, <a href="http://www.amazon.com/Programming-WCF-Services-Mastering-AppFabric/dp/0596805489/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1330443734&amp;sr=1-1">Programming WCF Services by Juval Lowy</a>, <a href="http://www.amazon.com/Essential-Windows-Presentation-Foundation-WPF/dp/0321374479">Essential WPF by Chris Anderson</a>, <a href="http://www.amazon.com/Silverlight-4-Action-Pete-Brown/dp/1935182374/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1330443873&amp;sr=1-1">Silverlight 4 in Action by Pete Brown</a>, and <a href="http://www.amazon.com/Pro-ASP-NET-MVC-Professional-Apress/dp/1430242361/ref=dp_ob_image_bk">Pro ASP.NET MVC by Steve Sanderson</a>.</p>
<p>Best of luck on your career development!</p>
<p><strong>C# Phone Screen Questions (with Answers):</strong></p>
<p>1. What kind of type is a string?<br />&nbsp;&nbsp;&nbsp; &gt; reference<br />2. What kind of type is a double?<br />&nbsp;&nbsp;&nbsp; &gt; value<br />3. What keyword defines a custom value type?<br />&nbsp;&nbsp;&nbsp; &gt; struct<br />4. Can a class have more than one direct base class?<br />&nbsp;&nbsp;&nbsp; &gt; no<br />5. What keyword makes a member visible to inherited classes?<br />&nbsp;&nbsp;&nbsp; &gt; protected<br />6. What keyword makes a class visible only within its assembly?<br />&nbsp;&nbsp;&nbsp; &gt; internal<br />7. What keyword allows a method to be overridden?<br />&nbsp;&nbsp;&nbsp; &gt; virtual<br />8. What keyword requires a method to be overridden?<br />&nbsp;&nbsp;&nbsp; &gt; abstract<br />9. What keyword prevents a class from being used as a base class?<br />&nbsp;&nbsp;&nbsp; &gt; sealed<br />10. What keyword returns true if a cast will succeed?<br />&nbsp;&nbsp;&nbsp; &gt; is<br />11. What keyword returns null if a cast will not succeed?<br />&nbsp;&nbsp;&nbsp; &gt; as<br />12. What keyword ensures code execution even if an exception occurs?<br />&nbsp;&nbsp;&nbsp; &gt; finally<br />13. What keyword calls IDisposable.Dispose?<br />&nbsp;&nbsp;&nbsp; &gt; using<br />14. What keyword constrains a generic type argument to derive from a particular class?<br />&nbsp;&nbsp;&nbsp; &gt; where<br />15. What two keywords used together return IEnumerable&lt;T&gt;?<br />&nbsp;&nbsp;&nbsp; &gt; yield return<br />16. What keyword would you use to define an inline variable in a LINQ query?<br />&nbsp;&nbsp;&nbsp; &gt; let<br />17. What keyword brings an extension method into scope?<br />&nbsp;&nbsp;&nbsp; &gt; using<br />18. What keyword do you add to a delegate to force subscribers to use += or –=?<br />&nbsp;&nbsp;&nbsp; &gt; event<br />19. What method do you call on a delegate to run it on a background thread?<br />&nbsp;&nbsp;&nbsp; &gt; BeginInvoke<br />20. What keyword provides thread synchronization?<br />&nbsp;&nbsp;&nbsp; &gt; lock</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/400/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/400/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/400/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=400&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/02/28/screening-c-candidates-lets-play-20-questions/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>
	</item>
		<item>
		<title>2011 Recap</title>
		<link>http://blog.tonysneed.com/2012/01/31/2011-recap/</link>
		<comments>http://blog.tonysneed.com/2012/01/31/2011-recap/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 19:15:00 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=397</guid>
		<description><![CDATA[After a rather long break from blogging, it’s time for me to jump back in!&#160; I thought I would start by taking a look back at 2011 and recapping some of my experiences, with a sneak peek at blogging topics &#8230; <a href="http://blog.tonysneed.com/2012/01/31/2011-recap/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=397&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After a rather long break from blogging, it’s time for me to jump back in!&nbsp; I thought I would start by taking a look back at 2011 and recapping some of my experiences, with a sneak peek at blogging topics I plan to cover in the next several weeks.</p>
<p>On a personal level, we added a new member to our family: Kornelius Aaron Sneed, born February 8, 2011.&nbsp; He is the youngest of our three children.&nbsp; My oldest is Kerrigan, age 6, followed by Karisma, age 3.&nbsp; My wife, Zuzana, holds the whole family together.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="Sneed Kids" border="0" alt="Sneed Kids" src="http://tonysneed.files.wordpress.com/2012/01/img_0724.jpg?w=346&h=259" width="346" height="259"></p>
<p>From a professional standpoint, 2011 was also an interesting year.&nbsp; I continued to work as an instructor for <a href="http://www.develop.com/technicalstaff#Tony-Sneed">DevelopMentor</a>, but I started to spend much more time doing hands-on software development for various clients in the Dallas area.&nbsp; My first client was a pharmaceutical distribution company that was porting two applications, one a Windows Forms app and the other an ASP.NET app, over to a single <a href="http://www.silverlight.net/">Silverlight</a> app that would run both in-browser and out-of-browser.&nbsp; That gig ended in July, when I picked up some WCF work in Fort Worth building an external-facing REST-ful WCF service, as well as some internal-facing queued WCF services.&nbsp; Then I picked up an <a href="http://www.asp.net/mvc">ASP.NET MVC</a> project in Plano, Texas, creating a web portal hosting several ASP.NET and Silverlight apps.&nbsp; That morphed into a project building a Security Token Service using <a href="http://msdn.microsoft.com/en-us/security/aa570351">Windows Identity Foundation</a> by customizing the <a href="http://identityserver.codeplex.com/">Thinktecture Identity Server</a> authored by <a href="http://www.leastprivilege.com/">Dominick Baier</a>.</p>
<p>It was at that time that I decided to write my own MVVM Toolkit, which I called “<a href="http://www.silverlight.net/">Simple MVVM Toolkit</a>,” first targeting it for Silverlight, and then adding support for both WPF and Windows Phone.&nbsp; It took me a few weeks to put out the first version.&nbsp; Then I spent the better part of the next four months adding features, putting together sample apps and documentation, writing an installer, and performing some screencasts.&nbsp; I also spent a great deal of time answering questions posted to my blog and the <a href="http://simplemvvmtoolkit.codeplex.com/discussions">project discussion board</a> at CodePlex.&nbsp; My New Year’s resolution is to incorporate some requested features and add support for Silverlight 5.</p>
<p>With the advent of my toolkit, I started blogging more often, holding forth on a variety of topics, including WCF, REST, Data Services, ASP.NET MVC, and the Onion Architecture.&nbsp; In June of 2010, when I migrated my blog to <a href="http://wordpress.com/">WordPress.com</a>, I was receiving about 3,000 hits per month.&nbsp; Now it’s over 11,000 visitors per month, with 110 followers from all over the world.&nbsp; In the past 12 months I’ve had over 15,000 downloads of my Simple MVVM Toolkit.&nbsp; The project discussion board has over 100 threads, and the Silverlight-MVVM Facebook Group has 34 members.&nbsp; What’s so cool about all this is the ability to have an impact and help others, even if they’re halfway around the globe.</p>
<p>On a more controversial note, last year I took the plunge and bought a 13” <a href="http://www.apple.com/macbookpro/">Apple MacBook Pro</a>.&nbsp; I had owned a <a href="http://en.wikipedia.org/wiki/Dell_Inspiron">Dell Inspiron</a> prior to that, but it was constantly overheating and I had to replace the power cord twice (at over $100 a pop).&nbsp; I already owned an iPhone and had purchased an iPad.&nbsp; So when the hard drive on my Dell started to fail, and researched the cost of going with a Mac.&nbsp; In total, it cost me about $2,000, with an <a href="http://www.intel.com/content/www/us/en/processors/core/core-i7-processor.html?iid=subhdr%20itc_core">i7 Intel processor</a>, 8 GB of RAM and a 240 GB solid state drive (which was not large enough).&nbsp; I bought the drive separately and swapped out the 500 GB SATA drive that came with the laptop, placing it in a case to use for backups.&nbsp; My main concern was how well I could run Windows on a Mac, but running Windows 7 using <a href="http://www.parallels.com/products/desktop/">Parallels</a> in <a href="http://www.parallels.com/landingpage/dskd19_2/?source=google_us&amp;gclid=CK7a6quAqJoCFRlcagod-gUg1w">Coherence</a> mode made the experience nearly seamless.&nbsp; Making this move came with a tinge of nostalgia, because my very first computer was the original Mac, which I purchased in 1984 and came with a single floppy (no hard drive) and 128K of RAM.&nbsp; Ironically, I paid $2,000 for it, which in today’s dollars amounts to $4000.</p>
<p>So what’s next for blogging?&nbsp; There are a couple of miscellaneous topics I’d like to cover, such as Behavior-Driven Development with SpecFlow, and some highlights of a presentation I did last Fall in WCF Data Services.&nbsp; Then I’d like to share what I learned about Windows Identity Foundation and the experience of customizing an open-source Security Token Service to achieve centralized authentication and authorization within an enterprise; how to perform single sign-in and support claims in a Silverlight app; and an approach to single sign-out and global session management across multiple applications secured by the same STS.</p>
<p>Cheers,<br />Tony</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/397/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/397/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/397/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=397&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2012/01/31/2011-recap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2012/01/img_0724.jpg" medium="image">
			<media:title type="html">Sneed Kids</media:title>
		</media:content>
	</item>
		<item>
		<title>OData, Where Art Thou?</title>
		<link>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/</link>
		<comments>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 14:53:59 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[OData]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/2011/11/11/odata-where-art-thou/</guid>
		<description><![CDATA[Gave a talk last night to the Dallas .NET Developer Group on OData and WCF Data Services. I’ll update this post with some info on the topic, but in the meantime you can download the slides and code for the &#8230; <a href="http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=393&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Gave a talk last night to the <a href="http://www.ddnug.net" target="_blank">Dallas .NET Developer Group</a> on <a href="http://www.odata.org/" target="_blank">OData</a> and <a href="http://msdn.microsoft.com/en-us/data/bb931106" target="_blank">WCF Data Services</a>.</p>
<p><a href="http://www.odata.org/"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="odata-logo" src="http://tonysneed.files.wordpress.com/2011/11/odata-logo.png?w=323&h=39" alt="odata-logo" width="323" height="39" border="0" /></a></p>
<p>I’ll update this post with some info on the topic, but in the meantime you can download the slides and code for the talk here: <a title="http://bit.ly/odata-talk" href="http://bit.ly/odata-talk">http://bit.ly/odata-talk</a>. Enjoy.</p>
<p>UPDATE: You can find a recording of this talk posted here: <a href="http://usergroup.tv/videos/odata-where-art-thou-publishing-odata-feeds-with-wcf-data-services">http://usergroup.tv/videos/odata-where-art-thou-publishing-odata-feeds-with-wcf-data-services</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/393/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/393/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/393/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=393&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/11/11/odata-where-art-thou/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/odata-logo.png" medium="image">
			<media:title type="html">odata-logo</media:title>
		</media:content>
	</item>
		<item>
		<title>More NLog Goodness</title>
		<link>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/</link>
		<comments>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 13:42:04 +0000</pubDate>
		<dc:creator>Tony Sneed</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[NLog]]></category>

		<guid isPermaLink="false">https://tonysneed.wordpress.com/?p=384</guid>
		<description><![CDATA[This is a follow-up to my post on Using NLog with Dependency Injection.&#160; There I showed how you can abstract away a specific logging implementation from your application by implementing a common interface and using a DI container, such as &#8230; <a href="http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=384&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a follow-up to my post on <a href="http://blog.tonysneed.com/2011/10/09/using-nlog-with-dependency-injection/" target="_blank">Using NLog with Dependency Injection</a>.&nbsp; There I showed how you can abstract away a specific logging implementation from your application by implementing a common interface and using a DI container, such as Ninject or StructureMap, to resolve the concrete implementation at runtime.&nbsp; This time around, I thought I would call out a few more features of NLog which I found useful.</p>
<p><em>Download the </em><a href="http://tonysneed.com/download/ninject-nlog.zip" target="_blank"><em>code</em></a><em> for this blog post.</em></p>
<p>One of the most common uses of logging is to record log entries in a database table. NLog has an interesting feature that allows you to include the table definition in your NLog.config file and run a command-line utility to create the database and logging table, as well as set up other targets, such as a Windows Event Log or performance counters.&nbsp; To take advantage of this feature, you need to run the NLog installer, which you can download from <a href="http://nlog.codeplex.com/releases/view/32639" target="_blank">here</a>.&nbsp; This will give you the documentation, Visual Studio item templates for sample configuration files, schemas for XML intellisense in config files, extended layout renderers, and the config-driven installer utility.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-items" border="0" alt="nlog-items" src="http://tonysneed.files.wordpress.com/2011/10/nlog-items.jpg?w=612&h=403" width="612" height="403"></p>
<p>To find these goodies, you need to go to the directory where NLog is installed after running the setup program, which is probably <strong>&#8220;%ProgramFiles(x86)%\NLog\.NET Framework 4.0&#8243;</strong>.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-install-dir" border="0" alt="nlog-install-dir" src="http://tonysneed.files.wordpress.com/2011/10/nlog-install-dir.jpg?w=505&h=366" width="505" height="366"></p>
<p>A common question is where to place the NLog config file.&nbsp; There are a number of <a href="http://nlog-project.org/wiki/Configuration_file#Configuration_file_locations" target="_blank">options</a>.&nbsp; If you want to perform logging at the class library level, and perhaps have a logging test project, you may want to place the NLog.config at the solution level, and link to it from projects where you want to perform logging.&nbsp; To do this, right-click on the project and select Add Existing Item.&nbsp; Then navigate to the solution directory where you placed the NLog.config file and, instead of clicking the Add button, select the drop-down on the Add button and choose <strong>Add As Link</strong>.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="add-as-link" border="0" alt="add-as-link" src="http://tonysneed.files.wordpress.com/2011/11/add-as-link.jpg?w=597&h=365" width="597" height="365"></p>
<p>Then select properties for the linked file and set <strong>Copy to Output Directory</strong> to “Copy Always.”</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="nlog-props" border="0" alt="nlog-props" src="http://tonysneed.files.wordpress.com/2011/11/nlog-props.jpg?w=372&h=216" width="372" height="216"></p>
<p>For web apps, you’ll probably need to have a physical NLog.config file in the root directory (with Copy to Output Directory set to “Do Not Copy”), because placing the file in the bin directory does not seem to work (regardless of what the documentation states).</p>
<p>One change I wanted to make to my log output is to include the <strong>identity</strong> of the current user.&nbsp; If you look at the list of <a href="http://nlog-project.org/wiki/Layout_renderers" target="_blank">built-in layout renderers</a>, you’ll find the <a href="http://nlog-project.org/wiki/Identity_layout_renderer" target="_blank">${identity}</a> tag, which provides the identity of the thread’s current principal.</p>
<pre class="code"><span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
{
    <span style="color:green;">// Set user identity
    </span><span style="color:#2b91af;">Thread</span>.CurrentPrincipal = <span style="color:blue;">new </span><span style="color:#2b91af;">WindowsPrincipal</span>(<span style="color:#2b91af;">WindowsIdentity</span>.GetCurrent());

    <span style="color:green;">// Other code follows ...
</span>}</pre>
<p>In web applications, this will give you the application pool’s identity rather the end user’s identity.&nbsp; The <a href="http://nlog-project.org/wiki/Aspnet-user-identity_layout_renderer" target="_blank">${aspnet-user-identity}</a> tag will return the identity of the logged on user, but you can use only this tag if you reference the <strong>NLog.Extended.dll</strong> assembly.&nbsp; If you’re using NLog via NuGet, add the <strong>NLog for Extended Profile</strong> package, which will add the reference.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="nlog-ext" border="0" alt="nlog-ext" src="http://tonysneed.files.wordpress.com/2011/10/nlog-ext.jpg?w=619&h=331" width="619" height="331"></p>
<p>For an ASP.NET MVC app, you’ll need to include pieces from the <em>Internet Application</em> MVC3 template to enable users to authenticate via a LogOn view.</p>
<p><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="mvc-int" border="0" alt="mvc-int" src="http://tonysneed.files.wordpress.com/2011/10/mvc-int.jpg?w=484&h=440" width="484" height="440"></p>
<p>All you have to do to log on is run the app and register as a new user.&nbsp; A database will be created according to the “ApplicationServices” connection string in web.config.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="asp-user-reg" border="0" alt="asp-user-reg" src="http://tonysneed.files.wordpress.com/2011/11/asp-user-reg.jpg?w=488&h=421" width="488" height="421"></p>
<p>The next piece is enabling <strong>database logging</strong>. For this you simply create a logging target with xsi:type=&#8221;Database&#8221;.&nbsp; One of the issues I ran into is specifying the date-time in a format SQL Server understands. The <a href="http://nlog-project.org/wiki/Date_layout_renderer" target="_blank">${date}</a> tag accepts a format parameter that can be any argument accepted by DateTime.ToString(format). I found the standard “s” <a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Sortable" target="_blank">Sortable Format Specifier</a> to be a good choice.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">target </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">database</span>"
        <span style="color:red;">xsi:type</span><span style="color:blue;">=</span>"<span style="color:blue;">Database</span>"<span style="color:blue;">&gt;

  &lt;!-- </span><span style="color:green;">SQL command to be executed for each entry </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">commandText</span><span style="color:blue;">&gt;</span>INSERT INTO LogEvent(EventDateTime, EventLevel, UserName, MachineName, EventMessage, ErrorSource, ErrorClass, ErrorMethod, ErrorMessage, InnerErrorMessage) VALUES(@EventDateTime, @EventLevel, @UserName, @MachineName, @EventMessage, @ErrorSource, @ErrorClass, @ErrorMethod, @ErrorMessage, @InnerErrorMessage)<span style="color:blue;">&lt;/</span><span style="color:#a31515;">commandText</span><span style="color:blue;">&gt;

  &lt;!-- </span><span style="color:green;">parameters for the command </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventDateTime</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${date:s}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventLevel</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${level}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@UserName</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${identity}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@MachineName</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${machinename}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@EventMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${message}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorSource</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-source}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorClass</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-class}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorMethod</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-method}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@ErrorMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=error-message}</span>" <span style="color:blue;">/&gt;
  &lt;</span><span style="color:#a31515;">parameter </span><span style="color:red;">name</span><span style="color:blue;">=</span>"<span style="color:blue;">@InnerErrorMessage</span>" <span style="color:red;">layout</span><span style="color:blue;">=</span>"<span style="color:blue;">${event-context:item=inner-error-message}</span>" <span style="color:blue;">/&gt;

  &lt;!-- </span><span style="color:green;">connection string </span><span style="color:blue;">--&gt;
  &lt;</span><span style="color:#a31515;">dbProvider</span><span style="color:blue;">&gt;</span>System.Data.SqlClient<span style="color:blue;">&lt;/</span><span style="color:#a31515;">dbProvider</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Logging;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;

&lt;/</span><span style="color:#a31515;">target</span><span style="color:blue;">&gt;</span></pre>
<p>If you try running this straight away, you won’t notice anything unusual, even though no database logging has taken place – because you haven’t even created the database!&nbsp; If you want to find out if there’s a problem with logging, one thing you can do is configure the logger to throw exceptions.&nbsp; This will cause an exception to be raised in the logger if NLog cannot initialize a target, but problems writing to the database won’t come up. For that you’ll want to log internal NLog exceptions.</p>
<p><img style="background-image:none;border-bottom:0;border-left:0;padding-left:0;padding-right:0;display:inline;border-top:0;border-right:0;padding-top:0;" title="nlog-console-error" border="0" alt="nlog-console-error" src="http://tonysneed.files.wordpress.com/2011/11/nlog-console-error.jpg?w=620&h=248" width="620" height="248"></p>
<p>You can log them to the console, but in a real-world scenario, you’ll want to log NLog internal errors to a text file.&nbsp; That way, you can inspect it on the server where your app is deployed.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">nlog </span><span style="color:red;">xmlns</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.nlog-project.org/schemas/NLog.xsd</span>"
      <span style="color:red;">xmlns:xsi</span><span style="color:blue;">=</span>"<span style="color:blue;">http://www.w3.org/2001/XMLSchema-instance</span>"
      <span style="color:red;">throwExceptions</span><span style="color:blue;">=</span>"<span style="color:blue;">true</span>"
      <span style="color:red;">internalLogLevel</span><span style="color:blue;">=</span>"<span style="color:blue;">Error</span>"
      <span style="color:red;">internalLogFile</span><span style="color:blue;">=</span>"<span style="color:blue;">..\..\..\nlog-app.log</span>"<span style="color:blue;">&gt;</span></pre>
<p>This relative path will place the log in the solution directory for the project.&nbsp; However, the location of the internal log file for a web app will need to be determined at runtime, based on Server.MapPath.&nbsp; This means you’ll need to set the log file path in the Application_Start method of Global.asax.cs.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">MvcApplication </span>: System.Web.HttpApplication
{
    <span style="color:blue;">protected void </span>Application_Start()
    {
        <span style="color:blue;">string </span>nlogPath = Server.MapPath(<span style="color:#a31515;">"nlog-web.log"</span>);
        InternalLogger.LogFile = nlogPath;
    }
}</pre>
<p>Now that we can see errors generated by NLog, we need to create the database and table where we want to store our logs.&nbsp; NLog comes with a handy command-line tool called <strong>InstallNLogConfig.exe</strong>, which you can run on your NLog.config file.&nbsp; If the config file includes information about the definition of the database table, this tool will create the table for you.&nbsp; You can even have it drop and re-create the logging database.&nbsp; The tool will also create the windows event log or performance counters if those targets are specified.</p>
<pre class="code"><span style="color:blue;">&lt;!-- </span><span style="color:green;">command to install logging database </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;</span>CREATE DATABASE Logging<span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Master;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;</span>true<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;

&lt;!-- </span><span style="color:green;">command to create logging table </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
    </span>CREATE TABLE LogEvent(
    EventId int primary key not null identity(1,1),
    EventDateTime datetime,
    EventLevel nvarchar(50),
    UserName nvarchar(50),
    MachineName nvarchar(1024),
    EventMessage nvarchar(MAX),
    ErrorSource nvarchar(1024),
    ErrorClass nvarchar(1024),
    ErrorMethod nvarchar(1024),
    ErrorMessage nvarchar(MAX),
    InnerErrorMessage nvarchar(MAX))
  <span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">install-command</span><span style="color:blue;">&gt;

&lt;!-- </span><span style="color:green;">command to drop logging database </span><span style="color:blue;">--&gt;
&lt;</span><span style="color:#a31515;">uninstall-command</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;</span>DROP DATABASE Logging<span style="color:blue;">&lt;/</span><span style="color:#a31515;">text</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;</span>Data Source=.\SQLEXPRESS;Initial Catalog=Master;Integrated Security=True<span style="color:blue;">&lt;/</span><span style="color:#a31515;">connectionString</span><span style="color:blue;">&gt;
  &lt;</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;</span>true<span style="color:blue;">&lt;/</span><span style="color:#a31515;">ignoreFailures</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">uninstall-command</span><span style="color:blue;">&gt;</span></pre>
<p>Logging is one of those things we can take for granted – until we need it.&nbsp; NLog is a nice tool that can provide logging to multiple targets.&nbsp; I’ve just scratched the surface on what NLog can do.&nbsp; For more info, check out the NLog <a href="http://nlog-project.org/wiki/Documentation" target="_blank">docs</a> and download the NLog <a href="https://github.com/jkowalski/NLog/" target="_blank">source code</a>, which includes some good examples.&nbsp; You can download the code for this post <a href="http://tonysneed.com/download/ninject-nlog.zip" target="_blank">here</a>.&nbsp; Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/tonysneed.wordpress.com/384/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/tonysneed.wordpress.com/384/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/tonysneed.wordpress.com/384/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.tonysneed.com&#038;blog=14038854&#038;post=384&#038;subd=tonysneed&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.tonysneed.com/2011/10/31/more-nlog-goodness/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/878b354347e93c317b20a2a540f3ce04?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tonysneed</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-items.jpg" medium="image">
			<media:title type="html">nlog-items</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-install-dir.jpg" medium="image">
			<media:title type="html">nlog-install-dir</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/add-as-link.jpg" medium="image">
			<media:title type="html">add-as-link</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/nlog-props.jpg" medium="image">
			<media:title type="html">nlog-props</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/nlog-ext.jpg" medium="image">
			<media:title type="html">nlog-ext</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/10/mvc-int.jpg" medium="image">
			<media:title type="html">mvc-int</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/asp-user-reg.jpg" medium="image">
			<media:title type="html">asp-user-reg</media:title>
		</media:content>

		<media:content url="http://tonysneed.files.wordpress.com/2011/11/nlog-console-error.jpg" medium="image">
			<media:title type="html">nlog-console-error</media:title>
		</media:content>
	</item>
	</channel>
</rss>
