Posts Tagged ‘StructureMap’

Integrating StructureMap with WCF 4.0 REST Services

Monday, August 16th, 2010

Ok first things first this post borrows a lot of code from  Jimmy Bogard’s post from a couple of years ago entitled Integrating StructureMap With WCF so credit where credits due. However there are a couple of minor changes that you need to make in order to get StructureMap to work properly with your WCF RESTful service.

 

Create A Custom Instance Provider

This code is identical to Jimmy’s original code.

public class StructureMapInstanceProvider : IInstanceProvider

{

    private readonly Type _serviceType;

 

    public StructureMapInstanceProvider(Type serviceType)

    {

        _serviceType = serviceType;

    }

 

    #region IInstanceProvider Members

 

    public object GetInstance(InstanceContext instanceContext)

    {

        return GetInstance(instanceContext, null);

    }

 

    public object GetInstance(InstanceContext instanceContext, Message message)

    {

        return ObjectFactory.GetInstance(_serviceType);

    }

 

    public void ReleaseInstance(InstanceContext instanceContext, object instance)

    {

    }

 

    #endregion

}

 

Create A Custom Service Behaviour Class

This code is identical to Jimmy’s original code.

public class StructureMapServiceBehaviour : IServiceBehavior

   {

       #region IServiceBehavior Members

 

       public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

       {

           foreach (var endpointDispatcher in

               serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>().SelectMany(

                   channelDispatcher => channelDispatcher.Endpoints))

           {

               endpointDispatcher.DispatchRuntime.InstanceProvider =

                   new StructureMapInstanceProvider(serviceDescription.ServiceType);

           }

       }

 

       public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,

                                        Collection<ServiceEndpoint> endpoints,

                                        BindingParameterCollection bindingParameters)

       {

       }

 

       public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

       {

       }

 

       #endregion

   }

 

Create A Custom Service Host

This code is almost identical to Jimmy’s. The only difference is that your custom class should inherit from the WebServiceHost class rather than the normal ServiceHost class for normal WCF Services.

public class StructureMapWebServiceHost : WebServiceHost

{

    public StructureMapWebServiceHost()

    {

    }

 

    public StructureMapWebServiceHost(object singletonInstance, params Uri[] baseAddresses) : base(singletonInstance, baseAddresses)

    {

    }

 

    public StructureMapWebServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)

    {

    }

 

    protected override void OnOpening()

    {

        Description.Behaviors.Add(new StructureMapServiceBehaviour());

        base.OnOpening();

    }

}

 

Create A Custom Service Host Factory

Once again this code is almost identical to Jimmy’s. The only difference is that we inherit from WebServiceHostFactory rather than the usual ServiceHostFactory class.

/// <summary>

/// StructureMap Service Host Factory for WCF REST Services

/// </summary>

public class StructureMapWebServiceHostFactory : WebServiceHostFactory

{

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

    {

        return new StructureMapWebServiceHost(serviceType, baseAddresses);

    }

}

 

Wiring Up Our Route

In our Global.asax file create our route using the StructureMapWebServiceHostFactory rather than the normal WebServiceHostFactory.

public class Global : HttpApplication

{

    void Application_Start(object sender, EventArgs e)

    {

        IoC.RegisterDependencies();

 

        RegisterRoutes();

    }

 

    private void RegisterRoutes()

    {       

        RouteTable.Routes.Add(new ServiceRoute("ReferenceData", new StructureMapWebServiceHostFactory(), typeof(ReferenceData)));

    }

}

Inversion of Control and StructureMap: Part 1

Tuesday, November 10th, 2009

I’ve been asked at work to provide some documentation to the other guys on the team around Inversion of Control and how we should be using StructureMap on our projects. Nothing in these upcoming blogs is revolutionary or new and there is nothing that you couldn’t from countless other sources but I thought I would share it anyway. I hope its of use.

What is StructureMap?

StructureMap is an Inversion Of Control container. There are a few out there but essentially they all do the same thing:

  • StructureMap
  • Windsor Castle
  • Spring.Net
  • AutoFac
  • Unity
  • Ninject

Before we delve too much into the specifics of StructureMap I thought we should start with a little refresher course on Dependency injection and Inversion of Control.

What is Inversion Of Control?

Consider the following code:


class Class1
{
   public void SomeMethod()
   {
      var class2 = new Class2();

      class2.SomeOtherMethod();
   }
}

Class1 is always (tightly) coupled to Class2. Even if we wrap Class2 with an interface we are still coupled to the concrete implementation of Class2. Because Class1 creates our implementation of IClass2


class Class1
{
   public void SomeMethod()
  {
     IClass2 class2 = new Class2();

     class2.SomeOtherMethod();
  }
}

How do we get around this coupling? If Class1 doesn’t create Class2 but is given an instance of an object that is already created using its interface then Class1 will no longer be coupled to Class2.

We can pass into Class1 whatever implementation of IClass2 we want it could be the real implementation of Class2 or it could be a mock object. It can be anything we want it to be we have total freedom now.

When a class no longer creates the dependant classes it requires to do its work but is given them this is called dependency injection. We can do this in two ways using either the  Constructor or using properties.

In general constructor injection is the preferred approach, although there are times when you will need to use property injection. Class1 below has been refactored so that we now use constructor injection.


class Class1
{
   private readonly IClass2 _class2;

   public Class1(IClass2 class2)
   {
      _class2 = class2;
   }

   public void SomeMethod()
   {
      _class2.SomeOtherMethod();
   }
}

Poor Man’s Dependency Injection

So if we don’t create our dependencies in our classes anymore where do we create them? One solution is to use what is known as poor man’s dependency injection (PMDI), which is a technique where we incorporate two constructors on our class. One that injects our dependencies in through the constructor and a default constructor that creates the concrete implementations of our dependencies for us.

In our normal code we would use the default constructor but in our tests we would inject our mocks in through the testing constructor. See our refactored Class1 with that uses poor man’s dependency injection implemented.


// Testing Constructor – our dependencies can be
// injected using this constructor.
public Class1(IClass2 class2)
{
   _class2 = class2;
}

// Default Constructor – Our dependencies are created
// using this constructor.
public Class1():this(new Class2())
{
}

PMDI is great for implementing inversion of control for legacy code as it provides you with a way to decouple your code and test whilst limiting the extent of your refactoring because you are keeping your existing (default) constructor and hence are not breaking any existing code that depends on that class.

Why Don’t We Use Poor Man’s Dependency Injection All The Time?

Poor man’s dependency injection work’s ok, on smaller projects and as I said with legacy code. However what you find is that on larger projects with complex dependency graphs things can get out of control pretty fast and things can start hurting.

Consider the following scenario: ClassA has a dependency on ClassB, which in turn has a dependency on ClassC which in turn has a dependency on ClassD… ok you get the idea..All of a sudden the constructor for ClassA looks like this:

class ClassA
{
   public ClassA():this(new ClassB(new ClassC(new ClassD(new ClassE()))))   {}

   public ClassA(IClassB classB){}
}

Pretty ugly isn’t it. all the other classes would have equally nasty and complex constructors also. Now consider what would happen if I changed the signature of ClassE so that it now took an connection string.  This would mean that I would have to change the constructors on Classes A, B, C and D. Now all of a sudden dependency injection doesn’t seem like such a great idea and you want to strangle the guy that first ever suggested using it…and remember this is only for a trivial example.

IOC Container To The Rescue

An IOC container such as StructureMap handles these complexities and does all the heavy lifting for you.

The container knows about your interfaces and the concrete classes that implement those interfaces. It knows how to instantiate your objects in your domain and resolve their dependencies for you. It doesn’t matter how complex the dependency graph is any more because your IOC container will do it all for you. Once you start delving into IOC containers you realize that they can do loads of other cool things too but I’ll save that for later..

Testing your StructureMap Registries.

Monday, November 2nd, 2009

I find that on every project I work on which uses StructureMap I include the same three unit tests per Structuremap registry.

My TestFixture set up normally looks something like this..

        [TestFixtureSetUp]
        public void TestFixtureSetup()
        {
            // Act
            ObjectFactory.Initialize(x => x.AddRegistry(new MyRegistry()));
        }

My first tests makes use of the in built testing capabilities within StructureMap. If there are any problems with your registry they should be captured by this test.

        [Test]
        public void Assert_registry_is_valid()
        {
            // Assert
            ObjectFactory.AssertConfigurationIsValid();
        }

My second test isn’t really a test but is useful to have in your solution if you need to diagnose any StructureMap problems. Calling this will write out all the dependencies that are registered with your container to the output window.

         [Test]
        public void What_do_we_have()
        {
            Debug.WriteLine(ObjectFactory.WhatDoIHave());
        }

My third test checks that you have more than one dependency registered with your StructureMap container. What I have found is that it is possible to configure your registry incorrectly and StructureMap won’t load any dependencies at all. However when you call the AssertConfigurationIsValid method it returns true. When you run up your application you get the ‘No Default Instance defined for PluginFamily’ exception. This tests helps you get check for this scenario.

         [Test]
        public void Assert_container_is_not_empty()
        {
            // Assert
            Assert.IsTrue(ObjectFactory.Container.Model.AllInstances.Count() > 1);

        }

Refactoring Switch Statements With StructureMap

Friday, October 23rd, 2009

Switch statements are commonly regarded as code smells, especially when the number of switch statements becomes very large. For this example I’m going to show you the traditional approach to refactor out a switch statement in C# and how you can further refine this approach using StructureMap though this would be possible using any IOC container.

Consider the following switch statement which I’ve kept fairly simple for the purpose of  demonstration:

public void ProcessCommand(Command command)
        {
            switch (command)
            {
                case Command.Go:
                    Console.WriteLine("Go");
                    break;

                case Command.Pause:
                    Console.WriteLine("Pause");
                    break;

                case Command.Stop:
                    Console.WriteLine("Stop");
                    break;

                default:
                    throw new Exception("Unhandled Command");
            }
        }

The Classic Approach To Refactoring Switch Statements

Normally when refactoring a switch statement we would perform the following steps:

1) Create an abstract/interface for a handler e.g.

public interface ICommandHandler
{
    void Handle();
}

2) For each case statement create a concrete implementation of our abstract handler  e.g.

 public class GoHandler:ICommandHandler
    {
        public void Handle()
        {
            Console.WriteLine("Go");
        }

        public bool Handles(Command type)
        {
            return Command.Go == type;
        }
    }

3) Create a Dictionary of our handlers using our switch statement key for our dictionary key e.g.

    public class RefactoredWithDictionary
    {
        private readonly Dictionary _commandHandlers;

        public RefactoredWithDictionary()
        {
            _commandHandlers = new Dictionary
                                   {
                                       {Command.Go, new GoHandler()},
                                       {Command.Pause, new PauseHandler()},
                                       {Command.Stop, new StopHandler()}
                                   };
        }

        public void DoSomethingWithTheSwitchStatement(Command command)
        {
            _commandHandlers[command].Handle();
        }
    }

Ok this is a big improvement from our previous switch statement it helps us get a bit closer to our S.O.L.I.D code Nirvana by adhering to our single responsibility principle and encapsulating our logic in specific handlers. However if we need to add a new handler we will need to modify the code by adding a new handler to the dictionary which violates our Open Closed Principle.

StructureMap To The Rescue!

The first thing we need to do is modify our ICommandHandler interface slightly.

public interface ICommandHandler
{
        void Handle();
        bool Handles(Command command);
        bool IsDefault { get; }
}

We have added two methods to the Interface. The new Handles method means each concrete implementation can now return whether or not it can handle a specific Command and the IsDefault property tells us whether or not our Handler is the default handler or not.

Our concrete implementation would now look like this:

    public class GoHandler:ICommandHandler
    {
        public void Handle()
        {
            Console.WriteLine("Go");
        }

        public bool Handles(Command type)
        {
            return Command.Go == type;
        }

        public bool IsDefault
        {
            get { return false; }
        }
    }

Now our class that can take an IEnumerable collection of  ICommandHandlers and query the collection for a handler that can handle the particular command.  It can also query the collection for the default handler if there is no handler defined for the particular Command.

Our class that originally contained the switch statement now looks like this:

    public class RefactoredWithStructureMap
    {
        private readonly IEnumerable _commandHandlers;

        public RefactoredWithStructureMap(IEnumerable commandHandlers)
        {
            _commandHandlers = commandHandlers;
        }

        public void DoSomethingWithTheSwitchStatement(Command command)
        {
            var defaultHandler = _commandHandlers.Where(handler => handler.IsDefault).First();

            var commandHandler = _commandHandlers
                .Where(handler => handler.Handles(command))
                .DefaultIfEmpty(defaultHandler)
                .FirstOrDefault();

            commandHandler.Handle();
        }
    }

Great but we need to make one more change so that we can get StructureMap to inject in our Handlers. We Need to modify our StructureMap Registry to do two things. Firstly we need to tell StructureMap to load all implementations of ICommandHandler. Secondly we need to tell StructureMap how to satisfy any requests for IEnumerable<ICommandHandler> and how to construct that collection.

To do this we need to add the following lines to our Registry.

    internal class StructureMapRegistry : Registry
    {
        public StructureMapRegistry()
        {
            Scan(scanner =>
                     {
                         scanner.TheCallingAssembly();
                         scanner.WithDefaultConventions();
                         scanner.AddAllTypesOf();
                     });

            ForRequestedType>()
                .TheDefault.Is.ConstructedBy(x => ObjectFactory.GetAllInstances());
        }
    }

The beauty of this approach is now if we need to add a new handler all we have to do is write a new handler and it will automatically be injected into our class by StructureMap!

kick it on DotNetKicks.com

Tags: ,
Posted in .NET, S.O.L.I.D | No Comments »