Basic Log4Net step-up

The following post explains how to get Log4Net working in a .NET console application.

The first step is create your console application and add references to Log4Net. The easiest way to add the correct references is via NuGet, where it is simply listed as log4net.

You’ll need to add a configuration file to tell Log4Net how you want it to log. A basic example would be:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>

  <log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="Test.log" />
      <appendToFile value="true" />
      <maximumFileSize value="5000KB" />
      <maxSizeRollBackups value="50" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%utcdate{yyyy-MM-dd HH:mm:ss.fffffff} - %level - %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingFile" />
    </root>
  </log4net>
  
</configuration>

This example simply adds a rolling log file. It’s called rolling because it starts a new log file at triggered intervals, allowing you to delete historical log files when you’ve finished with them. In this case, a new log file is started each time the current log file gets to 5000KB. It’s worth taking a look at the Log4Net documentation to find out about the different types of logging available. It is also possible to write your own appender if you want to do something not already built it to Log4Net.

In order to tell Log4Net to pick your configuration, you need to add the following to your application:

[assembly: XmlConfigurator]

The most obvious place for this is the AssemblyInfo.cs file.

This tells Log4Net to look in the default configuration file for the Log4Net configuration settings, but you can also tell Log4Net to look in another custom configuration file using the overloads available to the XmlConfigurator, although I prefer to keep all configuration in a single file.

Then it’s just a case of using the logger:

using System;
using log4net;

namespace Test
{
    public static class Program
    {
        public static void Main()
        {
            var log = LogManager.GetLogger(typeof(Program));
            log.Debug("Test console application started");

            Console.ReadLine();
        }
    }
}

Note that the LogManager returns an object implementing the ILog interface.

If you’re using dependency injection, you should wire up the dependency injector to return your ILog instance. The following shows how to do this if you’re using Castle Windsor:

using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using log4net;

namespace Test
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterLog(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                    .Instance(container));
        }

        private static void RegisterLog(WindsorContainer container)
        {
            container.Register(
                Component.For<ILog>()
                    .Instance(LogManager.GetLogger(typeof(Injector)))
                    .LifestyleSingleton());
        }
    }
}

The following statement will return an ILog instance as expected:

var log = Injector.Instance.Resolve();

There you have it!

Testing Windows Services with dependency injection

Last year I wrote a post on Testing Windows Services. I pointed out that recompiling and installing your Windows Service following each change is a really inefficient way to develop and test a service. Instead, I suggest that you can run and debug your service in Visual Studio simply by wrapping the service up in a test console application.

I said that I would revisit the post for services using dependency injection, so here goes. Note that the code in this article follows on directly from the code in the previous article, so you’ll need to read the previous article in order for this to make sense!

First, a quick discussion as to how you could add dependency injection to a Windows Service:

I believe the easiest way to use dependency injection in a .NET Windows Service application is to use the dependency injection engine to inject required services into the ServiceBase.Run() method in the Program class for the service:

using System.ServiceProcess;

namespace MyService
{
    public static class Program
    {
        public static void Main()
        {
            var servicesToRun = new[] { (ServiceBase)Injector.Instance.Resolve() };
            ServiceBase.Run(servicesToRun);
        }
    }
}

In order to do this, you simply need to create an empty interface for your service, which the service implements:

namespace MyService
{
    public interface IService
    {
        // No implementation
    }
}
using System.IO;
using System.ServiceProcess;

namespace MyService
{
    public partial class Service : ServiceBase, IService
    {
        public Service()
        {
            InitializeComponent();
        }

        // Service implementation...
    }
}

My original article gave an example of a service which creates and deletes a file when it starts and stops. To complete the example, let’s extract the file interaction code out as a dependency. Here’s the interface:

namespace MyService
{
    public interface IFileCreator
    {
        void Create();
        void Delete();
    }
}

…and here’s the implementation:

using System.IO;

namespace MyService
{
    public class FileCreator : IFileCreator
    {
        public void Create()
        {
            using (var stream = new FileStream("Running", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("Running");
                    writer.Flush();
                }
            }
        }

        public void Delete()
        {
            var fileInfo = new FileInfo("Running");
            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }
        }
    }
}

The injector class for the service would then look something like this:

using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace MyService
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterService(container);
            RegisterFileCreator(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For()
                .Instance(container));
        }

        private static void RegisterService(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(Service)));
        }

        private static void RegisterFileCreator(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(FileCreator)));
        }
    }
}

Note that I’ve wired up both the service (using IService) and my new FileCreator class.

The ServiceWrapper class would be exactly as in the previous example. The only change to the wrapper console application would be to change the Program, as follows:

using System;
using MyService;

namespace MyServiceWrapper
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var serviceWrapper = new ServiceWrapper();

            // Wire up service dependencies here:
            serviceWrapper.FileCreator = Injector.Instance.Resolve();

            try
            {
                serviceWrapper.TestStart();
                Console.ReadLine();
                serviceWrapper.TestStop();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error: " + exception.Message);
                Console.ReadLine();
            }
        }
    }
}

Unfortunately, in this class I’ve had to wire up all the dependencies in the ServiceWrapper manually as I haven’t found a way to do this automatically. However, this one small pain point is a significant improvement compared to compiling and installing your service each time you make a change!

Encapsulated and strongly-typed access to .NET configuration files with dependency injection

This article builds on a previous post entitled Encapsulated and strongly-typed access to .NET configuration files. In this example I’ll be adding dependency injection using Castle Windsor.

As per my previous post, the code for this example is in GitHub, here:

https://github.com/stevebarker333/Injected-Encapsulated-Strongly-Typed-Configuration-Files

In this post I’ll assume that you’ve read the previous post, and that you have the existing code base as a starting point. The first step then, is to add Castle Windsor to the project using NuGet. This adds references to each project as follows:

ConfigurationDependencyInjection01

Since dependency injection works by resolving interfaces to types, each encapsulated ConfigurationFile will need to be given an interface by adding IConfigurationFile to each of the two UI projects:

ConfigurationDependencyInjection02

These new interfaces need contain only the properties that are unique to each UI. Access to core properties is achieved via the ICoreConfiguration, as follows:

UI1.Configuration.ConfigurationFile:

using System;
using API.Configuration;

namespace UI1.Configuration
{
    public interface IConfigurationFile : ICoreConfiguration
    {
        string UI1String { get; }
        int UI1Int { get; }
        Uri UI1Uri { get; }
    }
}

UI2.Configuration.ConfigurationFile

using System;
using API.Configuration;

namespace UI2.Configuration
{
    public interface IConfigurationFile : ICoreConfiguration
    {
        string UI2String { get; }
        int UI2Int { get; }
        Uri UI2Uri { get; }
    }
}

The definitions of the ConfigurationFile classes in each UI project need to be adjusted to include these new interfaces, as follows:

public class ConfigurationFile : 
    API.Configuration.ConfigurationFile, IConfigurationFile, 
    API.Configuration.ICoreConfiguration
{
    ...
}

Each UI then gets its own Injector class:

ConfigurationDependencyInjection03

…containing the following code:

UI1.DependencyInjection.Injector:

using API.Configuration;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using UI1.Configuration;
using API;

namespace UI1.DependencyInjection
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterConfiguration(container);
            RegisterWidget(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                .Instance(container));
        }

        private static void RegisterConfiguration(WindsorContainer container)
        {
            container.Register(
                Component.For<IConfigurationFile, ICoreConfiguration>()
                .ImplementedBy(typeof(Configuration.ConfigurationFile))
                .LifeStyle.Singleton);
        }

        private static void RegisterWidget(WindsorContainer container)
        {
            container.Register(
                Component.For<IWidget>()
                .ImplementedBy(typeof(Widget))
                .LifeStyle.Singleton);
        }
    }
}

UI2.DependencyInjection.Injector:

using API.Configuration;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using UI2.Configuration;
using API;

namespace UI2.DependencyInjection
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;
        
        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterConfiguration(container);
            RegisterWidget(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                .Instance(container));
        }

        private static void RegisterConfiguration(WindsorContainer container)
        {
            container.Register(
                Component.For<IConfigurationFile, ICoreConfiguration>()
                .ImplementedBy(typeof(Configuration.ConfigurationFile))
                .LifeStyle.Singleton);
        }

        private static void RegisterWidget(WindsorContainer container)
        {
            container.Register(
                Component.For<IWidget>()
                .ImplementedBy(typeof(Widget))
                .LifeStyle.Singleton);
        }
    }
}

Note that the technique described in my post entitled Allowing Castle Windsor to resolve two interfaces to the same instance allows the ConfigurationFile type to be accessed using both the API interface ICoreConfiguration and each of the UI interfaces, IConfigurationFile. Note also that the Widget is registered with the dependency injector. This requires some small changes to the Widget and the creation of an interface, IWidget:

using System;
using API.Configuration;

namespace API
{
    public class Widget : IWidget
    {
        public ICoreConfiguration Configuration { get; set; }

        public void DoSomething()
        {
            Console.WriteLine(Configuration.CoreString);
            Console.WriteLine(Configuration.CoreInt);
            Console.WriteLine(Configuration.CoreUri);
        }
    }
}
namespace API
{
    public interface IWidget
    {
        void DoSomething();
    }
}

Finally, we change the Program classes in the console applications to use the injector, as follows:

using System;
using UI1.Configuration;
using API;
using UI1.DependencyInjection;

namespace UI1
{
    public static class Program
    {
        public static void Main()
        {
            var configurationFile = Injector.Instance.Resolve<IConfigurationFile>();

            Console.WriteLine(configurationFile.UI1String);
            Console.WriteLine(configurationFile.UI1Int);
            Console.WriteLine(configurationFile.UI1Uri);

            var widget = Injector.Instance.Resolve<IWidget>();
            widget.DoSomething();

            Console.ReadLine();
        }
    }
}
using System;
using UI2.Configuration;
using API;
using UI2.DependencyInjection;

namespace UI2
{
    public static class Program
    {
        public static void Main()
        {
            var configurationFile = Injector.Instance.Resolve<IConfigurationFile>();

            Console.WriteLine(configurationFile.UI2String);
            Console.WriteLine(configurationFile.UI2Int);
            Console.WriteLine(configurationFile.UI2Uri);

            var widget = Injector.Instance.Resolve<IWidget>();
            widget.DoSomething();

            Console.ReadLine();
        }
    }
}

Since the Widget class contains a property called Configuration of type ICoreConfiguration, the dependency injection engine can simply load the correct configuration file object in at run-time, and everything “just works”. Running the application gives exactly the same outputs as the previous non-injected example which means the spirit of the original code has been kept the same:

ConfigurationDependencyInjection04

ConfigurationDependencyInjection05

So, as always, adding dependency injection involves a bit more work, but the benefits (non-brittle, highly testable code to name just two) far outweigh the extra time required.

Allowing Castle Windsor to resolve two interfaces to the same instance

There are times when it’s useful to be able to resolve two different interfaces to the same type when using Castle Windsor for dependency injection. Given a class called MyClass which implements two interfaces, IOne and ITwo, the following code will achieve this:

container.Register(
                Component.For<IOne, ITwo>()
                .ImplementedBy(typeof(MyClass))
                .LifeStyle.Singleton);

This can be simply demonstrated using the following classes:

namespace TwoInterfaces
{
    public interface IOne
    {
        string GetMessage();
    }

    public interface ITwo
    {
        string GetMessage();
    }

    public class MyClass : IOne, ITwo
    {
        public string GetMessage()
        {
            return "Hello World!";
        }
    }
}

…in a console application. Running the following program class:

using System;

namespace TwoInterfaces
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var injector = Injector.Instance;

            var one = injector.Resolve<IOne>();
            var two = injector.Resolve<ITwo>();

            Console.WriteLine(one.GetMessage());
            Console.WriteLine(two.GetMessage());
            Console.WriteLine(one.Equals(two));

            Console.WriteLine("Press RETURN to exit...");
            Console.ReadLine();
        }
    }
}

…yields:

CastleWindsorTwoInterfaces

…as expected. My post entitled Basic dependency injection with Castle Windsor explains how to set up a fully working Castle Windsor injector in more detail.

ASP.NET MVC controller dependency injection using Castle Windsor

In a previous post I looked at basic dependency injection. In this post I demonstrated dependency injection using a simple example in which all functionality in the application was wrapped up in a single class (TimeWriter) with an associated interface (ITimeWriter). The application uses the dependency injection framework to get an instance of this class by its interface. In the process of doing this, all dependencies within the class are also satisfied. The application can then run as normal and write the date and time to the screen.

This approach is fine for console applications as they usually only have one entry point (the Main method) and from there we have complete control over the all code that runs once the application has started. Including dependency injection in ASP.NET MVC web-applications isn’t so straightforward as by default we don’t have control over how code runs right from the start of a user request. The MVC routing engine interprets the request, maps this to a controller, instantiates the controller (using the default controller factory) and calls the correct method on the controller instance. We then get to steer the code execution within the controller method. From a programming perspective, MVC development is like writting an application with multiple entry points contained in multiple controllers.

As we don’t get to instantiate the controller for ourselves there is no obvious way to include dependency injection, unless we write a class and interface for every controller operation and register them with the dependency injection engine in an analogous fashion to the console application example. This would work but it’s clearly not a good idea!

Fortunately ASP.NET MVC allows us to specify custom controller factories, and Castle Windsor includes classes to make it very simple to include dependency injection in this customisation process. Once configured, you can include dependencies as properties in your controllers which, along with the controllers themselves, are resolved by Castle Windsor each time a user request is received.

This time I’m starting with an Empty ASP.NET MVC application using the Razor view engine. The application and the containing solution are called ControllerInjection. Once created, I use NuGet to add a reference to Castle Windsor. My starting point thus looks like this:

Controller Injection 01

As in my basic dependency injection post I’m going to use Watch and IWatch as my example dependencies:

using System;

namespace ControllerInjection
{
    public interface IWatch
    {
        DateTime GetTime();
    }
}
using System;

namespace ControllerInjection
{
    public class Watch : IWatch
    {
        public DateTime GetTime()
        {
            return DateTime.Now;
        }
    }
}

These have been added to the solution as follows:

Controller Injection 02

Now I’m going to include a controller called HomeController:

Controller Injection 03

This contains the following code:

using System.Web.Mvc;

namespace ControllerInjection.Controllers
{
    public class HomeController : Controller
    {
        public IWatch Watch { get; set; }

        public ActionResult Index()
        {
            var text = string.Format("The current time on the server is: {0}", Watch.GetTime());
            return Content(text);
        }
    }
}

The key point here is the property called Watch with type IWatch. This is the dependency which will be injected at runtime. To save having to write a new view the Index method returns raw content.

The next component to implement is our custom controller factory. I’ve included this in a folder called DependencyInjection:

Controller Injection 04

The code inside ControllerFactory is as follows:

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel;

namespace ControllerInjection.DependencyInjection
{
    public class ControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public ControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }

            return (IController)kernel.Resolve(controllerType);
        }
    }
}

This class extends the DefaultControllerFactory, overriding the methods to get and release controllers. Note that the Castle Windsor kernel is used to resolve each controller by the type of controller required.

The next thing to add is a dependency injector:

Controller Injection 05

using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace ControllerInjection.DependencyInjection
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterControllers(container); 
            RegisterTimeComponents(container);
            
            return container;
        }

        private static void RegisterTimeComponents(WindsorContainer container)
        {
            container.Register(
                Component.For<IWatch>()
                .ImplementedBy(typeof(Watch))
                .LifeStyle.Singleton);
        }
        
        private static void RegisterControllers(WindsorContainer container)
        {
            var controllerFactory = new ControllerFactory(container.Kernel);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);

            container.Register(
                    Classes.FromThisAssembly()
                    .BasedOn(typeof(IController))
                    .If(t => t.Name.EndsWith("Controller"))
                    .If(t => t.Namespace.StartsWith("ControllerInjection.Controllers"))
                    .Configure(c => c.LifestylePerWebRequest()));
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                .Instance(container));
        }
    }
}

This is very similar to the injector in my basic dependency example, apart from the addition of a method to register controllers. Crucially, this method also registers our customer controller factory. Note that the lifestyle of each controller is set using LifestylePerWebRequest. This ensures that each new request gets its own controller instance.

As the controller factory is only registered once the injector singleton instance has been instantiated, we need to make sure that we initialise the injector when the application starts up. I’ve done this in the Application_Start method of the Global.asax class:

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using ControllerInjection.DependencyInjection;

namespace ControllerInjection
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // Ensure the dependency injection has been initalised:
            var injector = Injector.Instance;

            /* Normally you would do something with the injector here, like writing an entry to 
             * the log stating that the application had started. */

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

In practice this doesn’t prove to be a problem as most applications will involve some kind of logging tool (such as Log4Net) which will be obtained from the dependency injection engine. It is usual to log the fact that the application starts, so the injector gets instantiated anyway.

Running the code results in the following string being written to the screen as expected:

The current time on the server is: 11/04/2013 21:59:36

Basic dependency injection with Castle Windsor

I’ve already blogged about dependency injection using Castle Windsor in a previous article:

Registering many like types in Castle Windsor

…without giving any of the details around how to set up dependency injection in the first place. This post aims to put that right by demonstrating a basic “Hello World” for those new to dependency injection with Castle Windsor. My example application will simply write the current date and time to the screen using a console application.

I’ve created a solution called BasicDependencyInjection and added a console application with the same name. Don’t forget to change the client profile in your console application as described in a previous post.

I’ve used NuGet to add Castle Windsor to the console application.

My starting solution now looks like this:

Basic DI 01

To this I’ve added a class called Injector in a folder called DependencyInjection:

Basic DI 02

The code in this file is as follows:

using Castle.Windsor;
using Castle.Windsor.Installer;
using Castle.MicroKernel.Registration;

namespace BasicDependencyInjection.DependencyInjection
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);

            /* Register more components here */
            
            return container;
        }
        
        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                .Instance(container));
        }
    }
}

This is using a take on the singleton pattern to ensure there can only ever be one injector in the application. Note that the class also uses simple thread-locking to ensure that the singleton pattern isn’t bypassed by multiple threads requesting an instance at the same time.

Aside: These days the singleton pattern is considered bad practice. I believe the reason for this is that anything that would traditionally have been created using this pattern should now be injected. However, there is no way to “inject the injector” so I think use of the singleton pattern for this specific task is acceptible. I’d be interested to hear other opinions on this.

At the moment the only thing the injector can resolve is itself. We’ll add to the injector later on in the example. Next we need to create some test dependencies to inject.

When doing demonstrations using dependency injection I like to involve the current date and time as this is a classic textbook example of a dependency, and one that is often overlooked. If you’re hardcoding DateTime.Now statements throughout your code you haven’t removed all your dependencies! Other than making code loosely coupled one of the main advantages of dependency injection is that code is more testable. If you hardcode DateTime.Now you make unit testing much harder as test data needs to be generated each time to reflect the date on which the tests are being ran.

For dependency injection to work we need a class and an interface for each dependency, so I’m going to add Watch and IWatch to the application as follows:

Basic DI 03

These contain the following simple code:

using System;

namespace BasicDependencyInjection
{
    public interface IWatch
    {
        DateTime GetTime();
    }
}
using System;

namespace BasicDependencyInjection
{
    public class Watch : IWatch
    {
        public DateTime GetTime()
        {
            return DateTime.Now;
        }
    }
}

I’m also going to include a dependency to actually write the date and time to the screen, using ITimeWriter and TimeWriter:

Basic DI 04

…which are as follows:

namespace BasicDependencyInjection
{
    public interface ITimeWriter
    {
        void WriteTime();
    }
}
using System;

namespace BasicDependencyInjection
{
    public class TimeWriter : ITimeWriter
    {
        public IWatch Watch { get; set; }

        public void WriteTime()
        {
            Console.WriteLine("The current time is: {0}", Watch.GetTime());
        }
    }
}

The TimeWriter class has a property of Type IWatch called Watch, which doesn’t appear to be assigned a value anywhere in the code. One of the most confusing things for developers new to dependency injection is where these properties actually get set. When debugging through existing codebases with dependency injection enabled properties such as these do have values assigned but the assignment cannot be found anywhere. It’s like magic! The thing to remember is that when a reference is resolved using a dependency injecton framework, all contructor arguments and properties that have an interface that the injector knows about are assigned the object associated with the interface.

Now that dependencies have been added, we need to make sure the injector knows about them. I’ve updated the injector class as follows:

using Castle.Windsor;
using Castle.Windsor.Installer;
using Castle.MicroKernel.Registration;

namespace BasicDependencyInjection.DependencyInjection
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterTimeComponents(container);
            
            return container;
        }
        
        private static void RegisterTimeComponents(WindsorContainer container)
        {
            container.Register(
                   Component.For()
                   .ImplementedBy(typeof(Watch))
                   .LifeStyle.Singleton);

            container.Register(
                   Component.For()
                   .ImplementedBy(typeof(TimeWriter))
                   .LifeStyle.Singleton);
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For<IWindsorContainer>()
                .Instance(container));
        }
    }
}

This now maps IWatch to Watch and ITimeWriter to TimeWriter.

All that remains is to include some code in the program:

using System;
using BasicDependencyInjection.DependencyInjection;

namespace BasicDependencyInjection
{
    public static class Program
    {
        public static void Main()
        {
            var timePrinter = Injector.Instance.Resolve();
            timePrinter.WriteTime();

            Console.WriteLine();
            Console.WriteLine("Press RETURN to exit...");
            Console.ReadLine();
        }
    }
}

…and run the thing. Which yields:

Basic DI 05

…as expected.

That concludes my dependency injection “Hello World”.

Registering many like types in Castle Windsor

Castle Windsor is an awesome dependency injection framework available for use with .NET. While a full explanation of dependency injection is beyond the scope of this post, two key reasons to use a dependency injection framework are:

1) Code using dependency injection is less “tightly-coupled” and thus less brittle.
2) Dependency injection is vital in order to achieve true test driven development (incorporating unit-testing and mocking).

Anyone familiar with Castle Windsor will know that individual types can be registered as follows:

container.Register(
                Component.For<IUserRepository>()
                .ImplementedBy(typeof(UserRepository))
                .LifeStyle.Transient);

However, it is often the case that we have many “like” classes in an application, all providing similar functionality and having a similar naming convention. A good example would be respository classes, particularly when using ORM frameworks. Rather than manually adding each repository to the dependency container, Castle Windsor has a neat shortcut for registering multiple classes:

container.Register(Classes.FromAssemblyContaining(typeof(UserRepository))
                .Where(type => type.Name.EndsWith("Repository"))
                .If(type => type.Namespace.StartsWith("MyApplication.Api.Data.Repositories"))
                .WithService.FromInterface(typeof(IRepository))
                .Configure(c => c.LifestyleTransient()));

The code above will find all classes implementing the interace IRepository in the namespace MyApplication.Api.Data.Repositories (and its children) that have Repository at the end of their name. These can then be accessed at runtime using:

var userRepository = injector.Resolve<IUserRepository>();
var productRepository = injector.Resolve<IProductRepository>();

Very cool!