Showing posts with label Ioc. Show all posts
Showing posts with label Ioc. Show all posts

Friday, September 6, 2013

Using IoC for Runtime Plug-ins

If you are already using an IoC container in your code it can be easier to leverage it to create a plug-in model. (Instead of using a plug-in framework like MEF - which is still valid, but you may not want to introduce another similar paradigm into your code).


You'll need to add the following to the app.config so that plug-in DLL's will be in the probing path.
 

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath=".\Plugin" />
    </assemblyBinding>
</runtime>



This is where the plug in DLLs will be saved at runtime. In your composition root the plug-ins assemblies will need to be loaded into the AppDomain so the IoC container can find the plug in types.

public class AssemblyMetadata
{
    public string FileName { get; set; }
   
    public string Path { get; set; }
}

public class PlugInAssemblyLoader
{
    public void DiscoverAssembliesInPlugInFolder(string path, Predicate<AssemblyMetadata> assemblyFilter)
    {
        if (!File.Exists(path))
        {
            return;
        }

        var assemblies = Directory.GetFiles(path).Where(f => Path.GetExtension(f) == ".dll").Select(f => new AssemblyMetadata {FileName = Path.GetFileName(f), Path = f});
        assemblies = assemblies.Where(a => assemblyFilter(a));
        foreach (var assemblyFile in assemblies)
        {
            Assembly.LoadFile(assemblyFile.Path);
        }
       
        LoadAssembliesIntoAppDomain(discoveredAssemblies);
    }
}

public class CompositionRoot
{
    public void MapTypes()
    {
        // Other type registrations with your IoC container...omitted...
       
        // Load any (if any) plugin libraries into memory
        string plugInLibraryLocation = AppDomain.CurrentDomain.BaseDirectory + @"\Plugin"; // Or look up from app.config etc
        new PlugInAssemblyLoader().DiscoverAssembliesInPlugInFolder(plugInLibraryLocation, metadata => metadata.FileName.StartsWith("MyCompany"));
       
        // Be sure to trigger loading app.config registrations for your IoC container. This is where your plugins will be registered.


        // Plugin types could be replacement for standard types necessary in the application, or they could be optional plugins (ie additional filters e
    }
}




Friday, January 27, 2012

Using IoC for Extensibility

MEF is probably a better choice if you know up front there is a good likelihood of consumers wanting to extend your application by injecting their own types.  However, I think there are a few exceptions to this rule.

Firstly, most modern software applications make extensive use of IoC to loosely couple dependencies and allow easy unit testing.  Also, sometimes you don't think it is likely someone will want to swap out a class, but don't want to rule it out either.  Building in MEF support for unlikely cases is a waste of time in my opinion, especially if there are ways to override behaviour using the IoC mechanisms you're already using. In these cases I prefer to allow consumers to override the IoC registered types.

I did a post some time ago on how to prevent IoC configuration chaos (refering to the explosion in size of your app.config if you put all registrations in it). This post discusses using code registrations and a mechanism to automatically run the registration code for each assembly on start-up.

This idea can be extended to allow custom extensions to be added.

By default Unity doesn't allow types to be registered that are not referenced by the application (I think Structure Map doesn't allow this either).

Scenario 1)
A consumer of an application that is already fully completed wants to change some behaviour in that application, and they do not have the source code, just the binaries. The application uses the IoC pattern referenced by the blog post above.
The consumer can create a new application project that references everything the original application and basically wraps around it. The new application includes any new  references required to new assemblies containing classes you want to use in IoC registration.  On start-up the new application simply delegates into the original. Now you can customise the IoC mappings in the App.Config of the new application. This works great for windows services, web services, console applications, and some UI applications. This is the preferable scenario.

Scenario 2)
Another option is to customise the IoC pattern described in the blog post mentioned above. When the initialisation process is looking referenced assemblies in the AppDomain, you can add some IO code to scan for assemblies in a folder.  These new assemblies can be loaded with reflection and added into the AppDomain. Once this initialisation process is complete the App.Config can be applied. This is less desirable because the author of the original application has little control over how customisation are used by the original system. Potentially a security risk.
You could modify the reflection assembly loading mechanism to only allow assemblies with a certain signing key for example to mitigate this security concern.

Saturday, July 23, 2011

Unity Snippets

MSDN Article Introducing Unity
http://msdn.microsoft.com/en-us/library/cc816062.aspx

Policy Injection and Interception with Unity (Ent Lib 5 April 2010)
http://msdn.microsoft.com/en-us/library/ff660891(v=PandP.20).aspx

MSDN Article April 2011 Policy Injection with Unity
http://msdn.microsoft.com/en-us/magazine/gg598927.aspx

Usage scenarios for Interception and limitations and trade-offs
http://msdn.microsoft.com/en-us/library/ff660890(v=PandP.20).aspx

Saturday, April 23, 2011

How to show a dialog in MVVM

In Mvvm you do not want direct references from your controllers (aka View-Models, I find it easier to call them controllers for simplicity).  This means you don't want code that specifically calls Window.Show or MessageBox.Show.  The reason is basically two-fold:

  1. First you will be unable to unit test the controller.  Message-boxes or Dialogs popping open will halt the test.
  2. If you decide to share some code with another project that uses a different UI technology, then not following Mvvm explicitly will prevent this. Also common is stakeholders changing their minds.
The solution is to make use of an Inversion of Control container (aka factory).



Message Box Usage

Message boxes pose a problem for unit testing because when open they block the thread from completing, meaning user intervention is required to continue a test. This is not acceptable. To circumvent this, MessageBox use can be accessed via an interface.

private IMessageBoxService backingMessageBoxService;
public IMessageBoxService MessageBox {
    get {
        return this.backingMessageBoxService ?? (this.backingMessageBoxService = new WpfMessageBoxService());
        }

        private set {
            // Provided for testing
            this.backingMessageBoxService = value;
        }
    }
}



The above code works in production, but during testing a mock will need to be injected into the MessageBox property.

        [Test(Description = "The save action should trigger a message box")]
        [Timeout(500)]
        public void SuccessfulSaveMessage() {
            var controller = new FormController(new ContactDataServiceStub());
            var accessor = new FormController_Accessor(controller);
            var messageBoxMock = new MessageBoxServiceMock();
            accessor.MessageBox = messageBoxMock;
 
            // Click the save button in the same way the View xaml would in production.
            controller.SaveCommand.Execute(controller.CurrentContact);
 
            Assert.IsTrue(messageBoxMock.WasShowCalled);
        }


public interface IGlassDemoDialog {
    event EventHandler Closed;
    void Show();
}

And from within your controller you can get a reference to the dialog through the use of an object factory (or using an interfaced property shown previously in this document).

var glassDialog = ObjectFactory.Container.GetInstance<IGlassDemoDialog>();
glassDialog.Show();

This of course assumes you have a registration with the object factory either in the app.config or in startup.

ObjectFactory.Initialize(init => {
    // Other config lines here
    init.For<IGlassDemoDialog>().Use<WpfGlassWindowDemo>();
});

Finally, your custom interface must be implemented by your View.
public partial class WpfGlassWindowDemo : Window, IGlassDemoDialog { }


[Test]
public void ShowGlassWindowTest() {
    var controller = new RighthandController();
    var mockRepository = new MockRepository();  // Rhino Mock
    var dialogMock = mockRepository.StrictMock<IGlassDemoDialog>();
    dialogMock.Expect(dialog => dialog.Show());
    mockRepository.ReplayAll();  // Prepare mocks.
    ObjectFactory.Initialize(init => {
        init.For<IGlassDemoDialog>().Use(dialogMock);
    });
    Assert.IsTrue(controller.GlassCommand.CanExecute(null));
    controller.GlassCommand.Execute(null);
    mockRepository.VerifyAll(); // Guarantee all mocks were used appropriately.
}  

Saturday, April 16, 2011

MEF versus IoC

The Microsoft Extensibility Framework (MEF) has been around for a couple of years now and is used to allow extension to Windows applications without changing the original code (Recomposition).  It can be used with either Silverlight, WPF, and WinForms. MEF is not a replacement to PRISM. The PRISM toolkit to help you implement the MVVM pattern and is similar to MVVM Light or any of the other MVVM Toolkits. PRISM is also only intended for WPF and Silverlight.  So what is MEF?  The MEF Website describes it as
"Application requirements change frequently and software is constantly evolving. As a result, such applications often become monolithic making it difficult to add new functionality. The Managed Extensibility Framework (MEF) is a new library in .NET Framework 4 and Silverlight 4 that addresses this problem by simplifying the design of extensible applications and components."


I've been a long standing fan of IoC, and after reading many articles about MEF and writing a few test applications, there seems to be a cross over with IoC.  IoC is far more generic and is a more broad pattern to use across your entire system, whereas MEF is specifically targeting extending and recomposition of the UI.  So where's the cross over?  MEF is a kind of object factory (aka container), it makes replacement of UI Views and Controllers (aka View-Models) easy.  By decorating a public property with an attribute the MEF framework with find all subclasses of (or a chosen one) and instantiate it and inject it into the property.  Very much like an IoC container.  But MEF does have some cool features for searching application folders for runtime add-ins etc.  But so does StructureMap.

Here's an excellent comparison from MSDN:

My take on it, is MEF will suit people new to IoC better, and might be more approachable. The documentation for MEF is pretty good, better than StructureMap's documentation for sure.  Using a mature feature rich IoC container like StructureMap however you get most of the functionality of MEF, but it requires a little more work to use. But it gives you the advantage of a unified approach and good consistency.

Thursday, September 2, 2010

Microsoft Patterns & Practice's Prism Demo

References:

Summary (from the official Microsoft Site)

Prism (Composite Application Guidance for WPF and Silverlight) is designed to help you more easily build enterprise-level Windows Presentation Foundation (WPF) client applications. This guidance will help you design and build flexiblecomposite client applications-composite applications use loosely coupled, independently evolvable pieces that work together in the overall application.
The Composite Application Guidance can help you develop your client application in a modular fashion. With this approach, you manage the complexity of a large application by breaking it down into smaller, simpler modules. The modules can evolve independently while working together as a unified application.
This version of the Composite Application Guidance is designed to help you build applications in WPF and Silverlight that have a single code base.


Architectural Goals

The Composite Application Library is designed to help architects and developers achieve the following objectives:
  • Create a complex application from modules that can be built, assembled, and, optionally, deployed by independent teams using WPF or Silverlight.
  • Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development.
  • Use an architecture that promotes reusability across independent teams.
  • Increase the quality of applications by abstracting common services that are available to all the teams.
  • Incrementally integrate new capabilities.

Messaging and Event Aggregators

Comparing the Prism offering of Event Aggregator and with Mvvm Light, is clear that Mvvm Light is a far nicer syntax.

Mvvm Light Event Aggregator - Send a Message / Event Notification

Messenger.Default.Send(new NotificationMessage(this, "Show Modal Dialog"));

Mvvm Light Event Aggregator - Receive a Message / Event
Messenger.Default.Register<NotificationMessage>(this, SomeEventHandlerMethod);

Compare that with the Prism Event Aggregator:

Sender:
NotificationEvent x = eventAggregator.GetEvent<NotificationEvent>();
x.Publish("Show Modal Dialog");


Listener:
NotificationEvent x = eventAggregator.GetEvent<NotificationEvent>();
x.Subscribe(message => SomeEventHandlerMethod(message));

Yep... I know which one I prefer.

I don't think I'll look any closer at Prism (or MEF or whatever its called this month) until I need more loose coupling with internal components.

Monday, July 26, 2010

External Dependency Wrapping and Unit Testing

A project I am currently working on requires us to reference a third party assembly.  As is quite often the case the assembly is not exposing types that are unit testing friendly.  Ideally interfaces or abstract base classes would be great, but this is seldom the case.  I've been refining a strategy to consume dependencies in a indirect manner so the hard coded types don't work their way through my code essentially having a "Medusa" effect. IE: Casting all of my types into stone and then they too cannot be replaced with test mocks.
Consider the schematic diagram below.  The blue assembly is the Medusa assembly, wanting to cast all my types into stone. But wait I have a magic mirror shield! The External Type Factory.  This is intended to control the creation of types I need to consume from the external assembly.  The other issue is being able to invoke methods in the external assembly that require the hard types(Widget, Color, and Thing) as parameters.  The External Type Factory has adaptor methods to unwrap my wrappers back to their original types in an indirect manner to stop the petrification effect.



The good:
  • Stops the external hard types from preventing unit testing.
  • Can also have life cycle management benefits - ie all calls to the assembly are managed through one area of code allowing other benefits such as life cycle management (correct instantiation and disposal) and logging.
  • Fits well with IoC containers.
  • Allows tossing the external dependency away and replacement with something else at a future date with little effort.

The bad:
  • A slight overhead of more code.
  • A slight overhead of more complexity with the indirection.
  • You still need to ensure that all developers use your factory instead of going direct and preventing unit testing.
  • All types that want to use the external assembly need to have a factory available to them to be able to get the types.
  • Not really usable in XAML code.

I might add detail to this as I continue the journey down this path.

Sunday, July 25, 2010

Using the Factory Pattern as an Assembly Gateway

Sometimes its useful to tightly control access to a framework or utility assembly to ensure it is either used correctly or is easy to use.  We as developers are guilty of often building in too much flexibility, and too much always equates to more complexity.  This normally results in questions from consuming developers like:

 "How do I use this, there seems to be more than one way to do anything?"

Having one way to do anything can sometimes create a intuitive and easy to use API.  Having only one way to do certain things obviously has trade offs in flexibility, it very much depends on the use case of your utility assembly and the consequences if consumers misuse it.  My personal preference is to think about possible extensions and where functionality could be added but not necessarily expose them publically or add the extension code at all until there is a demand for them. (Demand > 1 BTW).

Its also worth considering implementing strict and few use cases for your assembly if its consumers are likely to be unit testing.  A Test Driven Developer will want to have your babies if you are exposing nothing but interfaces and all references between objects are interfaces and creation is controlled through an interfaced factory.  Not to mention that using this approach means your consumers are forced to write code that is unit testable.

Enter the Factory Method Patten.

Basically, using a factory, will create an object for you and return you a reference through an interface. You are not in control what exact concrete type is behind the interface nor should you care, as long as you get an instance with the right interface.  The factory is also interfaced so that when it comes time to test, you can use a different factory or change its configuration to return a different type. (See IoC containers).

Here's a schematic diagram showing the idea of using a factory as a gateway into a shared assembly:


Most types  within the assembly are "internal" (ie the class is declared as internal).  Each type that can be used externally are interfaced, and the interface is public.  All references to other types, refer to the other type using an interface. For example type C and type A both have a reference to type B, but instead of referencing B directly they reference an interface of B.  The Factory is responsible for creating types and returning a reference to an interface.  The factory itself also implements an interface to allow the entire Assembly to be replaced with a complete set of test Mocks.

Lets see a code example.  First lets start by looking at the end result usage:
The protected assembly in this example is the "InterfaceIntoAssembly" namespace.  


namespace ConsoleApplication1
{
    using System;
    using InterfaceIntoAssembly;

    /// <summary>
    /// A Test Console application
    /// </summary>
    public static class Program
    {
        private static IFactory factory;

        public static IFactory Factory
        {
            get
            {
                // If no factory has been supplied yet, create the factory live production
                // code will use.
                return factory ?? (factory = new Factory());
            }

            set
            {
                // Provided for testing (alternatively could be constructor argument).
                factory = value;
            }
        }

        /// <summary>
        /// Main entry point
        /// </summary>
        /// <param name="args">The command line args.</param>
        public static void Main(string[] args)
        {
            IConnection connection = Factory.CreateConnection();
            IMessage message = connection.CreateMessage();
            IMessage reply = message.CreateReply();
            connection.Send(reply);
        }
    }
}
This code is from a Console application that consumes the InterfaceIntoAssembly.DLL.  So to relate to the diagram above this code is from the "External Consumer of Assembly" green box. First thing to note is that I'm using a class scoped Factory property, this is to allow a Unit Test to create this class in test mode, and then inject a mocked Test Factory into the Factory property.  I prefer to have a property for a factory rather than pass it into the constructor of the class; although sometimes passing a factory into the constructor is necessary. You might ask why don't I just create an application wide static property and refer to the factory that way, much like using the StructureMapstatic ObjectFactory.CurrentContainer property?  When you run your tests with a multi-threaded parallel runner get back to me on the use of static object factories.

Lets look next at the Factory code:

namespace InterfaceIntoAssembly
{
    public class Factory : IFactory
    {
        public IMessage CreateMessage()
        {
            return new Message();
        }

        public IConnection CreateConnection()
        {
            return new Connection();
        }
    }
}
There are many ways to implement this, and this is the most basic.  For more flexibility reach straight for StructureMap.  
The methods available here are the Types that you want external consumers to be able to create. So if a consuming developer needs to be able to "new-up" a class you will instead of making that class public create a method here to create it.  Types that are only created internally and references are passed out of the assembly then you will not need a create method.

Finally lets take a look at the connection object to round out the example.


namespace InterfaceIntoAssembly
{
    using System;

    public interface IConnection
    {
        int Status { get; }

        IMessage Receive();

        void Send(IMessage message);

        IMessage CreateMessage();
    }

    internal class Connection : IConnection
    {
        public int Status { get; private set; }

        public IMessage Receive()
        {
            throw new NotImplementedException();
        }

        public void Send(IMessage message)
        {
            throw new NotImplementedException();
        }

        public void HiddenMember()
        {
            throw new NotImplementedException();
        }

        public IMessage CreateMessage()
        {
            throw new NotImplementedException();
        }
    }
}

Note that all references to other classes are to interfaces, or alternatively you could use abstract class if that suits better (but remember not to put code in it that will hinder different usages like testing etc).
Also note that "HiddenMember" does not appear externally outside the assembly. So from the consuming console application described above you cannot see this member.  This method perhaps should be declared as internal for clarity. All interface members must be declared as public.

I'm not using a IoC framework in this example, but you certainly can.  However my personal preference for framework or base level assemblies to avoid excessive dependencies unless there's a strong reason to include them.  This simple factory definitely does the job in this case.
I'm also intending on posting another example of consuming a third party DLL that does not expose interfaces, and how to write unit testable code against such a dependency.

When does this not work well?
  • When your framework/utility assembly has types you expect consumers to inherit from.
  • When you cannot anticipate all use cases of your framework assembly.
  • When your target audience is very senior level developers who know exactly what they are doing and want unforeseen and creative ways to extend your assembly. (In this case you'd still interface and probably just ditch the factory gateway).
When does it work well?
  • When the consequences of misusing your assembly are severe (memory leaks, financial loss etc).
  • When you are trying to make it very easy for consuming developers to use your API.
  • When you know your use cases up front and can reasonably anticipate possible extensions to your DLL.
  • When you are making extensive use of unit testing.

Note to self, when you read this again and have forgotten where the source code is, you can find it here.

Monday, April 19, 2010

Preventing IoC Configuration Chaos

After working with tightly coupled (read as "welded") existing code bases in many previous companies, when given a green fields opportunity, I want to ensure thorough use of IoC.  This is essential to allow automated testing. Automated testing is essential for efficient agile development.

The problem is, when you write a large system, that equates to a large config file.  Actually it will be an enormous config file.  This is unacceptable in my opinion for several reasons:

  1. Large XML / Config files are annoying to maintain, and easy to get wrong.
  2. There's no compile time checking and fast feedback for XML / Config files.
  3. Most of the time the config is static, no one will want to change it at runtime for a production system (excluding unit testing).
  4. The config is owned and stored in the app/web config but some of your DLL's are designed to be reused independently and whenever they are consumers need to find an example of config and copy and paste it.
Nasty.
So a good solution needs the following attributes:
  1. By default (with no consumer code or config) any individual DLL must own its own default config. If a consumer takes and consumes your DLL that's all they need.
  2. By default the IoC container must be preconfigured to return production instances.
  3. Any hard coded default must be override-able by config.
  4. It must be easy to trigger IoC container intitialisation on application startup.
  5. Ideally the consumer shouldn't have to maintain a list of DLL's to intitialise.
Here's some sample code that I have come up with that attempts to solves these with StructureMap.
The basic idea is that all interfaces and abstracts registered with IoC for the primary purpose of unit testing should be configured with code in a DLL specific "Startup" class.  Each Referenced assembly in the current AppDomain is "visited" using a psuedo-visitor pattern and its Startup class is located and executed.

Each assembly that contains IoC registrations that need to evaluated must be decorated with this custom attribute.

[assembly: AssemblyInitialization(typeof(MamalsStartup))]
This points to the startup class containing the code registrations. Here's an example of a Startup implementation:

public class MamalsStartup : IStartup
    {
        private readonly object syncRoot = new object();

        public bool IsInitialized { get; private set; }

        public void InitializeObjectFactory()
        {
            if (this.IsInitialized)
            {
                return;
            }

            lock (this.syncRoot)
            {
                if (this.IsInitialized)
                {
                    return;
                }

                var factory = ObjectFactory.Container;
                factory.Configure(config =>
                {
                    config.For<ICat>().Use<Cat>();
                    config.For<ICat>().Use<Cat>().Named("Felix").OnCreation(c => c.Name = "Felix");
                    config.For<IDog>().Use<Dog>();
                    config.For<IChapter>().Use<Chapter1>();
                });

                FrameworkInitialise.ObjectFactoryInitializeCompleted += this.OnObjectFactoryInitializeCompleted;
                this.IsInitialized = true;
            }
        }

        public void Shutdown()
        {
            // Trigger any shutdown / cleanup logic
        }

        private void OnObjectFactoryInitializeCompleted(object sender, System.EventArgs e)
        {
            // You can do any singleton registration here. Or any registrations that require other registrations have been completed.
            FrameworkInitialise.ObjectFactoryInitializeCompleted -= this.OnObjectFactoryInitializeCompleted;
        }
    }
Notice how I have made an event that fires once all IStartup.InitializeObjectFactory this is to allow complex registrations that require instances of standard objects or singletons to be available.  It also useful for kicking off any other intialisation that may be required.  There's also a ShutDown method, this is useful for tidying up any singleton registrations that implement IDisposable or other cleanup logic.

To trigger the whole process the consuming code only needs one line of code:


// Invoke Initialise to trigger the process of "visiting" all assemblies referenced and calling each assemblies
// startup class to configure the IoC container.
FrameworkInitialise.Initialise();

Here's the initialize method:

/// <summary>
        /// Initializes the AppDomain assemblies that have the <see cref="AssemblyInitializationAttribute"/>.
        /// </summary>
        public static void Initialize()
        {
            if (isInitialised)
            {
                return;
            }

            isInitialised = true;
            var current = AppDomain.CurrentDomain;
            current.AssemblyLoad += OnAssemblyLoad;
            current.ProcessExit += ProcessExit;

            var assemblies = (from assemblyName in Assembly.GetEntryAssembly().GetReferencedAssemblies()
                              where assemblyName.FullName.StartsWith(AssemblyPrefix, StringComparison.InvariantCultureIgnoreCase)
                              select Assembly.Load(assemblyName))
                             .AsParallel();

            var list = new Dictionary<int, AssemblyInitializationAttribute>();
            FindInitAttribute(assemblies, list);

            // Finding and accessing the AssemblyInitializationAttribute will instantiate it and its ctor will trigger that assembly's startup class.
            // By the time this point is reached all assemblies have had their Object Factories configured.
            var handler = ObjectFactoryInitializeCompleted;
            if (handler != null)
            {
                // Some Assemblies may be interested to be informed when all others have had their Object Factories configured.
                // This will allow them to perform any other intialisation code that requires dependent assemblies to be configured first.
                handler(null, EventArgs.Empty);
            }
        }

Tuesday, March 16, 2010

Inversion of Control - Structure Map

 have been evaluating Inversion of Control (IoC) containers and offerings lately to determine a good fit for a new project in Wpf.  I have looked at Unity, StructureMap, and Windsor (although only really a glance at Windsor). I've read a few articles as well comparing a few and there seems to be a consensus with like minded people like myself (fans of DSL style command-chaining and Lambda) in favour of StructureMap. Another reason to like StructureMap is the evident effort to keep pace with language changes and constant improvement in finding more concise ways to implement the IoC pattern.


Terminology:
I use the term factory to abbreviate IoC Container.

The only thing left to decide is how to configure it and which injection strategy to use.  

[Edit 10-June-2010]


Configuration
Options are:
Configuration by app.config, xml, or code.  
This seems to be an easy answer in my opinion.  If something needs to be customisable per user / install then that registration must go into the app.config / xml, otherwise code registration is much faster. Code registration also ensures everyone on the team gets new registration entries as my team does not share app.config files (developer preferences interfere).


    1 <?xml version="1.0" encoding="utf-8" ?>
    2 <configuration>
    3     <configSections>
    4         <section name="StructureMap" type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>
    5     </configSections>
    6 
    7     <StructureMap>
    8         <DefaultInstance
    9             PluginType="Framework.Logging.ILogWriter,Framework"
   10             PluggedType="Framework.Logging.Log4NetLogWriter,Framework"
   11             />
   12         <DefaultInstance
   13             PluginType="StructureMap.Testing.Widget.IRule,StructureMap.Testing.Widget"
   14             PluggedType="StructureMap.Testing.Widget.ColorRule,StructureMap.Testing.Widget"
   15             Color="Blue"
   16             Scope="Singleton"
   17             Name="TheBlueOne"/>
   18     </StructureMap>
   19 </configuration>
Example app.config.


    6             var existingInstance = new Widget();
    7             ObjectFactory.Initialize(init => {
    8                 init.For<ILogWriter>().Use<FakeLogWriter>();
    9                 init.For<IService>().Singleton().Use<MyService>();
   10                 init.For<IWidget>().Use(existingInstance);
   11                 init.For<IComplex>().Use(() => new ComplexToBuildObject());
   12             });
Example code configuration.

Usage Strategies:
This where it gets more complicated, and probably purely personal preference.  Options are:
  • Constructor Injection
  • Setter Injection
  • Lambda / Function builders
Constructor Injection
The most common usage is Constructor Injection.  This involves injecting dependencies into a public constructor at object creation time.

   42     public class TestConstructor {
   43         public TestConstructor(ITestSingleton singleton, ITestTransient transient) {
   44             this.SingletonProperty = singleton;
   45             this.TransientProperty = transient;
   46         }
   47 
   48         public ITestTransient TransientProperty { get; private set; }
   49 
   50         public ITestSingleton SingletonProperty { get; private set; }
   51     }
       



   18     [TestFixture]
   19     public class TestConstructorInjection {
   20         [Test]
   21         public void ConstructorInjection() {
   22             var factory = new Container(config => {
   23                 config.For<ITestSingleton>().Singleton().Use<TestSingleton>();
   24                 config.For<ITestTransient>().Use<TestTransient>();
   25             });
   26 
   27             var target = factory.GetInstance<TestConstructor>();
   28 
   29             Assert.IsNotNull(target.TransientProperty);
   30             Assert.IsInstanceOf<TestTransient>(target.TransientProperty);
   31             Assert.IsNotNull(target.SingletonProperty);
   32             Assert.IsInstanceOf<TestSingleton>(target.SingletonProperty);
   33         }
   34     }

Pros / Cons:
+ Not bad speed performance (see further on in this post)
+ Small amount of registration code (1 per dependency globally - ie if multiple classes use ITestSingleton no more registrations are required).
- Requires public constructor even if you do not want the class createable externally.

Setter Injection:
This is less common, but may be more desirable now with C# Object Initialisers favoured over constructors to simply set properties.  

   18     public class ClassWithPropertyDependencies {
   19         [SetterProperty]
   20         public ITestTransient TransientProperty { get; set; }
   21 
   22         [SetterProperty]
   23         public ITestSingleton SingletonProperty { get; set; }
   24     }

...



   26     [TestFixture]
   27     public class TestSetterInjection {
   28         [Test]
   29         public void SetterInjection() {
   30             var factory = new Container(init => {
   31                 init.For<ITestTransient>().Use<TestTransient>();
   32                 init.SetAllProperties(setter => setter.OfType<ITestTransient>());
   33 
   34                 init.For<ITestSingleton>().Singleton().Use<TestSingleton>();
   35                 init.SetAllProperties(setter => setter.OfType<ITestSingleton>());
   36             });
   37 
   38             var target = factory.GetInstance<ClassWithPropertyDependencies>();
   39             var singleton = factory.GetInstance<ITestSingleton>();
   40 
   41             Assert.IsNotNull(target.TransientProperty);
   42             Assert.IsInstanceOf<TestTransient>(target.TransientProperty);
   43             Assert.IsNotNull(target.SingletonProperty);
   44             Assert.IsInstanceOf<TestSingleton>(target.SingletonProperty);
   45             Assert.AreSame(singleton, target.SingletonProperty);
   46         }
          }

Pros / Cons:
- Requires a public constructor still for this to work with StructureMap. Error 202 is thrown if the TestMaster constructor is made internal
- Requires properties that need to be set to be public settable. If they are not they will not be populated. This pollutes the design and can lead to misuse of a class.
- Slowest for of initialisation.
+ Good level of configuration (2 lines per dependency that needs to be used globally).

Lambda / Function Builder:
This registers a function or lambda to create an object instead of simply a type (a builder pattern).

   18     public class LambdaBuilderMaster {
   19         public static LambdaBuilderMaster CreateInstance() {
   20             return new LambdaBuilderMaster {
   21                 TransientProperty = new TestTransient(),
   22                 SingletonProperty = new TestSingleton(),
   23             };
   24         }
   25 
   26         public ITestTransient TransientProperty { get; private set; }
   27 
   28         public ITestSingleton SingletonProperty { get; private set; }
   29     }


...


   39     [TestFixture]
   40     public class TestBuilderStrategy {
   41         [Test]
   42         public void LambdaOrFunctionBuilder() {
   43             var factory = new Container(init => init.For<LambdaBuilderMaster>().Use(LambdaBuilderMaster.CreateInstance));
   44 
   45             var target = factory.GetInstance<LambdaBuilderMaster>();
   46             var singleton = factory.GetInstance<ITestSingleton>();
   47 
   48             Assert.IsNotNull(target.TransientProperty);
   49             Assert.IsInstanceOf<TestTransient>(target.TransientProperty);
   50             Assert.IsNotNull(target.SingletonProperty);
   51             Assert.IsInstanceOf<TestSingleton>(target.SingletonProperty);
   52             Assert.AreSame(singleton, target.SingletonProperty);
   53         }
          }

The lambdas in this example can of course point to a function elsewhere in the application and the private accessory in LambdaBuilderMaster could still be used for testing.

Pros / Cons:
+ Does not require a public constructor.
+ Does not require inappropriate properties to be settable.
+ Best performance.
- Requires a great deal of registration (1 for every type used with the IoC factory).
- Build process adds complexity to code.

Performance:
Here is a test that compares different creation methods, not so surprising results.


   44         [Test]
   45         public void Performance() {
   46             const int CreateThisMany = 10000;
   47             long time;
   48             var results = new List<KeyValuePair<string, long>>(3);
   49 
   50             // StructureMap Setter Injection - requires a lot of configuration. 2 registrations for every property type that needs to be auto-filled.
   51             time = FactoryPerformanceTest(
   52                     new Container(config => {
   53                         config.For<ITestSingleton>().Use<TestSingleton>();
   54                         config.For<ITestTransient>().Use<TestTransient>();
   55                         config.SetAllProperties(setter => setter.OfType<ITestSingleton>());
   56                         config.SetAllProperties(setter => setter.OfType<ITestTransient>());
   57                     }),
   58                 CreateThisMany,
   59                 factory => factory.GetInstance<ClassWithPropertyDependencies>());
   60             results.Add(new KeyValuePair<string, long>("Setter Injection", time));
   61 
   62             // Control speed benchmark using "new"
   63             time = FactoryPerformanceTest(null, CreateThisMany, factory => new ClassWithPropertyDependencies {
   64                 TransientProperty = new TestTransient(),
   65                 SingletonProperty = new TestSingleton(),
   66             });
   67             results.Add(new KeyValuePair<string, long>("New Operator", time));
   68 
   69             // StructureMap Constructor Injection - requires no config to auto populate constructor arguments. Only 1 registration is needed per argument type globally.
   70             time = FactoryPerformanceTest(
   71                 new Container(config => {
   72                     config.For<ITestSingleton>().Use<TestSingleton>();
   73                     config.For<ITestTransient>().Use<TestTransient>();
   74                 }),
   75                 CreateThisMany,
   76                 factory => factory.GetInstance<TestConstructor>());
   77             results.Add(new KeyValuePair<string, long>("Constructor Injection", time));
   78 
   79             // StructureMap using builder functions/lambdas - will require a registration for every type that has dependencies - probably the most configuration.
   80             var builderFactory = new Container(
   81                 config => {
   82                     config.For<ITestSingleton>().Use<TestSingleton>();
   83                     config.For<ITestTransient>().Use<TestTransient>();
   84                 });
   85             builderFactory.Configure(
   86                 config => config.For<TestConstructor>().Use(
   87                     () => new TestConstructor(builderFactory.GetInstance<ITestSingleton>(), builderFactory.GetInstance<ITestTransient>())
   88             ));
   89             time = FactoryPerformanceTest(
   90                 builderFactory,
   91                 CreateThisMany,
   92                 factory => factory.GetInstance<TestConstructor>());
   93             results.Add(new KeyValuePair<string, long>("Function/Lambda builders", time));
   94 
   95             // AND THE WINNER IS...
   96             results.ForEach(result => System.Diagnostics.Debug.WriteLine("{0} = {1}ms", result.Key, result.Value));
   97         }
And my output:
***** IoCComparison.StructureMapPerformanceTest.StructureMapPerformance
Setter Injection = 200ms
New Operator = 1ms
Constructor Injection = 69ms
Function/Lambda builders = 20ms



***** IoCComparison.NinjectPerformanceTest.NinjectPerformance
Setter Injection = 594ms
New Operator = 2ms
Constructor Injection = 516ms
Function/Lambda builders = 521ms


Structure Map versus Ninject
Its clear to see based on the performance results above that the same usage scenarios through both frameworks that StructureMap is the clear winner.  The only downside I can see to StructureMap is that there is no support for Silverlight (Client Framework)... yet.  A recent post on Stack Overflow points to July/August 2010 for a Silverlight release of StructureMap.  I do however really like Ninject's mission statement to keep their framework simple. In terms of quality of documentation and widespread adoption, again, StructureMap seems to be the clear winner.

My Recommendation on IoC Usage:
  1. If your class is intended to be public createable then use Constructor Injection. This is less configuration and it exhibits auto-detect dependencies capability; meaning if someone adds a new parameter to the constructor, the factory may be able to populate it without a new registration.
  2. If a class is not intended to be public createable then use the Lambda / Function Builder strategy.  In addition it may sometimes be cleaner code to use this over constructor injection.  Having said that, if you have a constructor with many arguments it could indicate the class is in need of a refactor.
  3. Only in special cases use Setter Injection where there are very strong reasons that the above two methods are not appropriate. That means more than "I don't like the above two".
Service Locator Pattern (anti-pattern?)
IoC factories are quite often used as a Service Locator pattern.  This means a singleton instance is available globally throughout the application via a static class and property. For example:

    9     public static class ObjectFactory {
   10         public static IContainer Container { get; }
   11     }

This isn't overly bad until you consider if your code is sprinkled with this call all over the place, creating a tight dependency on a particular IoC and one instance of it.


19             var service = ObjectFactory.Container.GetInstance<IService>();



On the up side it minimises all other coupling quite nicely. So instead of having tight coupling with all components you only have tight coupling with one.

One major downside is unit testing.  Consider if you have hundreds of tests, with some running simultaneously, each trying to configure and use the static ObjectContainer all at once... not going to work well.

There is no easy way to completely eliminate these service locator calls. The key thing is to minimise the use of a static ServiceLocator call.

My simple strategy is to use a protected or private property of type IContainer. 


   23     public class Service : IService {
   24         public Service() : base() {
   25         }
   26 
   27         private IContainer factory = null;
   28         protected IContainer Factory {
   29             get {
   30                 if (this.factory == null) {
   31                     this.factory = ObjectFactory.Container;
   32                 }
   33 
   34                 return this.factory;
   35             }
   36 
   37             set {
   38                 this.factory = value;
   39             }
   40         }
   41     }

Generally, avoiding static references to the factory require passing the factory around, typically through the constructor.  The above strategy means that a lot of classes are not polluted with IContainer in their constructors.  It also means that you do not need to pass IContainer into a class just so it can pass it to another internally created class that needs it.  The whole idea of avoiding calls to ObjectFactory.Container is to allow testing and prevent cross-pollution issues with running parallel tests (at least thats where I always find Service Locator issues).  

To test the above example class, the test can instantiate it and then set the Factory property using a private accessor strategy (I use reflection to set these in tests, MsTest has a great private accessor feature).  

   70         [Test]
   71         public void TestService() {
   72             var target = new Service();
   73             var testFactory = new StructureMap.Container();
   74             PrivateAccessor.SetProperty(target, "Factory", testFactory);
   75             var result = target.DoSomething();
   76             // ... Test outcome etc
   77         }
There are a few ways to set private properties, lets not go into that now, suffice to say, my PrivateAccessor is simply using reflection to get the property and set it. But the above test works fine and will not compete with other tests for a shared static resource.


Production code does not need to concern itself with any special treatment of the class, and this is as it should be; test code should not pollute classes. The only caveat is that you cannot use the Factory property inside the constructor (this can be avoided with lazy loading of properties the same way the Factory property works).
...

   78             var service = new Service();
   79             var data = service.DoSomething();
...

As you can see nice clean production code that requires no special treatment to allow unit testing.

Hope that helps someone.
Cheers