When are Injections Fun? C# Dependency Injection Deep Dive

Evening all,

This post has been in the works for a while but, due to a wee bit of sickness and a sudden busy schedule outside of work, it’s been waiting in the wings for a little longer than it should have been. Apologies about that guys and girls!

Anyway, I wanted to expose a piece on Dependency Injection. There has been an ongoing slice of development, using this methodology, doing the rounds at work. However, I wanted to look at DI from the perspective of Containers (DI can exist without these, but I’m interested solely in this approach for the time being) and will be using Autofac as the showcase for this.

Dependency Injection In A Nutshell

Dependency Injection essentially encapsulates the idea of producing loosely-coupled, easily testable code whereby classes are not (in the case of coupling DI with interface usage) tied to each other using concrete types. Using a DI Container, it’s also possible for the caller to request an implementation via an interface and retrieve an object on demand, without the need to worry about what other dependencies the type requested may require. When things are interface-centric, it’s also a cinch to override implementations and, off the back of this, unit test specific type behaviour in a more isolated way.

The best explanation you’ll find, without a shadow of a doubt, is this one (enjoy!):

How to explain dependency injection to a 5-year-old?

When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.

What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.

Dependency Injection Sample

What follows is a fairly trivial application that implements an Autofac DI Container, and shows off a few basic DI concepts to boot. Firstly, here are the resources that I used to kick start this project:

Autofac Documentation
Autofac NuGet Gallery Reference

I found this particular TechEd video particularly interesting. It covers DI and Container usage from the perspective of Autofac, Unity and many others (although, leans more towards Autofac as the examples begin to get more fleshed out):

Deep Dive into Dependency Injection and Writing Decoupled Quality Code and Testable Software

This first snippet of code outlines the entry point for a small Console Application. The ConfigureApplicationContext method constructs a ContainerBuilder object, which is part of the Autofac namespace, using a RegisterApplicationTypes helper method. This method illustrates, on application start, the linking of interface types to concrete implementations. Notice the addition of the ‘SingleInstance’ call against the registration of the IConfigurationHelper implementing type, this is an interesting nugget that forces the same instance of a class, as opposed to a new instance, to be retrieved when required (via a request to the DI Container).

The FileCleaner classes Run method is then called (I’ve used a concrete type at this level but, of course, I could have referenced this via an interface also). The FileCleaner class constructor accepts, for the purposes of resolving types from the DI Container, an IProcessorLocator implementing object. You’ll see this isn’t passed in per say, the call to Application.Container.Resolve takes care of this ‘dependency’ for use, magic! You’ll see how the IProcessorLocator object gets used specifically in later examples (the comments here also expand on the concepts at work, so be sure to have a sift through).

using Autofac;
using DesktopCleaner.Helpers;
using DesktopCleaner.Implementations;
using DesktopCleaner.Interfaces;
using DesktopCleaner.Locators;
using System;

namespace DesktopCleaner
{
    /// <summary>
    /// Console Application Program Class, containing this applications
    /// entry point (Main) method.
    /// </summary>
    class Program
    {
        #region Constructor

        /// <summary>
        /// Static Main method representing this applications
        /// entry point.
        /// </summary>
        /// <param name="args">Any arguments from external sources.</param>
        static void Main(string[] args)
        {
            // Configure this applications DI Container
            ConfigureApplicationContext();
        }

        #endregion Constructor

        #region Private Static Helper Methods

        /// <summary>
        /// Private static helper method that configures this applications
        /// DI Container fully, ready for the applications life-time (as well
        /// as kicking off the core processing of this application via a FileCleaner instance).
        /// </summary>
        private static void ConfigureApplicationContext()
        {
            // Use the Autofac ContainerBuilder type to construct interface/concrete type mappings
            ContainerBuilder builder = RegisterApplicationTypes();

            // Construct our DI Container (for general use throughout the lifetime of our application in this case)
            Application.Container = builder.Build();

            // Create a cleanerHelper and 'run it' (the objects constructor will receive an IProcessLocator implementing object (ProcessorLocator) in this case due to the previous mappings)
            FileCleaner cleanOperationHelper = Application.Container.Resolve<FileCleaner>();
            if (cleanOperationHelper.Run())
            {
                Console.WriteLine("Cleaning Completed Successfully!");
            }
            else
            {
                Console.WriteLine("Cleaning Failed. Please check the logs (what a joke, there are none!).");
            }

            // Halt application before exit so we can inspect the output
            Console.ReadLine();
        }

        /// <summary>
        /// Private static helper method that creates a ContainerBuilder
        /// to map interfaces to concrete types (for DI loveliness). Return the builder
        /// to the caller (we're using this to called builder.Build() to setup our 'Container').
        /// </summary>
        /// <returns></returns>
        private static ContainerBuilder RegisterApplicationTypes()
        {
            // Instantiate a builder and map types as required
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<FileCleaner>();
            builder.RegisterType<ConfigurationHelper>().As<IConfigurationHelper>().SingleInstance();    // A special case here, demonstrate the use of SingleInstance()
            builder.RegisterType<FileHelper>().As<IFileHelper>();
            builder.RegisterType<ProcessorLocator>().As<IProcessorLocator>();                           // A cool little utility to get instances (so we don't have to new-up in classes using concrete types)

            return builder;
        }

        #endregion Private Static Helper Methods
    }
}

Absolutely not required, just for illustration purposes only, the following static class is simply used as an application level helper (for global access to the container). Not necessarily how you’d structure it, but makes the examples coming up easier to manoeuvre through.

using Autofac;

namespace DesktopCleaner.Helpers
{
    /// <summary>
    /// Public static class that holds application constants
    /// and shared helpers.
    /// </summary>
    public static class Application
    {
        #region Public Static Properties (CORE DI CONTAINER)

        /// <summary>
        /// Public static property (for use across this application
        /// </summary>
        public static IContainer Container { get; set; }

        #endregion Public Static Properties (CORE DI CONTAINER)

        #region Public Constants

        /// <summary>
        /// Public constant string representing the DesktopAppSettingKey
        /// key value (in the app.config).
        /// </summary>
        public const string DesktopAppSettingKey = "DesktopPath";

        #endregion Public Constants
    }
}

Next up, we need some interfaces. These represent key processes that our application is expected to implement (the catch being that these interfaces will be used to retrieve concrete implementations on demand, without the need to use the ‘new’ keyword in our classes). Note the last interface in this list, IProcessorLocator. Again, this is a linchpin type that will be passed to each class to retrieve all manner of other types (due to its use of a generic method) on demand. The result being here that using an IProcessorLocator, as a container wrapper, negates the need to pass multiple interfaces to a type’s constructor. We just pass this one interface supporting object instead (and this also means we don’t need data fields to store these instances either).

namespace DesktopCleaner.Interfaces
{
    /// <summary>
    /// Public ICleanerHelper support interface definition.
    /// </summary>
    public interface ICleanerHelper
    {
        #region Interface Methods

        /// <summary>
        /// Public method for ICleanerHelper support representing
        /// behaviour for a 'run' process method.
        /// </summary>
        /// <returns>True if the run processing is successful, otherwise false.</returns>
        bool Run();

        #endregion Interface Methods
    }
}

...

using System.Collections.Specialized;

namespace DesktopCleaner.Interfaces
{
    /// <summary>
    /// Public ICleanerHelper support interface definition.
    /// </summary>
    public interface IConfigurationHelper
    {
        #region Interface Methods

        /// <summary>
        /// Public method for IConfigurationHelper support to allow for behaviour
        /// to retrieve a 'setting' based on a 'key'.
        /// </summary>
        /// <param name="key">The key to transpose to a value.</param>
        /// <returns>The value that links to the specified key.</returns>
        string GetConfigurationSetting(string key);

        /// <summary>
        /// Public method for IConfigurationHelper support to allow for behaviour
        /// to retrieve a collection of 'setting' keys and values.
        /// </summary>
        /// <returns>A collection of settings (specialised NameValueCollection).</returns>
        NameValueCollection GetAllConfigurationSettings();

        #endregion Interface Methods
    }
}

...

using System.Collections.Generic;

namespace DesktopCleaner.Interfaces
{
    /// <summary>
    /// Public IFileHelper support interface definition.
    /// </summary>
    public interface IFileHelper
    {
        #region Interface Methods

        /// <summary>
        /// Public method for IFileHelper support to allow for behaviour
        /// to get a list of files based on the specified path (in some manner, based on implementation).
        /// </summary>
        /// <param name="path">The directory path to be used.</param>
        /// <returns>A list of files relating to the directory specified.</returns>
        List<string> GetFilesForPathAsList(string path);

        /// <summary>
        /// Public method for IFileHelper support to allow for behaviour
        /// to process a list of file names (in some manner, based on implementation). 
        /// </summary>
        /// <param name="fileList">Represents the list of files to operate on.</param>
        /// <returns>A boolean to represent if processing was successful.</returns>
        bool ProcessFiles(List<string> fileList);

        #endregion Interface Methods
    }
}

...

namespace DesktopCleaner.Interfaces
{
    /// <summary>
    /// Public IProcessorLocator support interface definition.
    /// </summary>
    public interface IProcessorLocator
    {
        #region Interface Methods

        /// <summary>
        /// Public method for IProcessorLocator support to allow for behaviour
        /// to get a 'processor' for any specified interface type (this should be constrained more
        /// in an ideal world).
        /// </summary>
        /// <typeparam name="T">The type to retrieve a processor class based on.</typeparam>
        /// <returns>A concrete class, depending on the implementation.</returns>
        T GetProcessor<T>();

        #endregion Interface Methods
    }
}

Here we have another ‘illustrative’ class that, as you’ll remember from our DI Container configuration, is marked as ‘Single Instance’ (just as an example). It simply interrogates the AppSettings of the app.config file to retrieve information, as required by calling code.

using DesktopCleaner.Interfaces;
using System.Collections.Specialized;
using System.Configuration;

namespace DesktopCleaner.Implementations
{
    /// <summary>
    /// Public ConfigurationHelper class that implements IConfigurationHelper
    /// to interrogate the applications app.config file (implementation can
    /// be modified however, as per the DesktopCleaner.UnitTests).
    /// </summary>
    public class ConfigurationHelper : IConfigurationHelper
    {
        #region Public Expression Bodied Methods

        // Again, illustration only, may abstract this into a differing format (use of lazy/properties, etc) - Methods are for demo purposes (for mocking up a functional class for DI usage)

        /// <summary>
        /// Gets access to the applications app.config AppSetting
        /// key/value pairs (as is).
        /// </summary>
        /// <returns></returns>
        public NameValueCollection GetAllConfigurationSettings() => ConfigurationManager.AppSettings;

        /// <summary>
        /// Gets access to the a particular AppSetting value, from the app.config
        /// file, based on the provided key.
        /// </summary>
        /// <param name="key">The AppSetting key to use when searching for a corresponding value.</param>
        /// <returns>A string denoting the matching value (based on key).</returns>
        public string GetConfigurationSetting(string key) => ConfigurationManager.AppSettings[key];

        #endregion Public Expression Bodied Methods
    }
}

The next couple of classes represent the bulk of our test application. There is nothing super special or uber magical here, so it should be easy to stick with. The idea behind this application is to move files from one location to another, tidying files after a successful move. This is all tied to configuration found in the app.config (which can, of course, be overridden as demonstrated later on by some example unit tests). Due to the use of interfaces, the implementation itself could differ greatly, however.

The key code lies in the constructor, that assigns a private data field with an object supporting the IProcessorLocator interface, allowing for type resolution in the other core methods in this class. Within the Run method the ‘processor locator’ is finally utilised to, on demand, locate and retrieve instances of IConfigurationHelper and IFileHelper supporting objects. We could, of course, have foregone the use of the ProcessLocator, and passed in all required interface types into this objects constructor. However, we would have incurred penalties for unrequired object creation and storage for types that, in reality, may not even be used by calling code (in this example I’m utilising all of the types anyway, but just mark it as a side note!). We have an example of some loosely-coupled code!

The CompareObjectsInDebug method is there just to illustrate that the call to processorLocator.GetProcessor is retrieving new objects/single instances as expected.

using DesktopCleaner.Helpers;
using DesktopCleaner.Interfaces;
using System;

namespace DesktopCleaner.Implementations
{
    /// <summary>
    /// Public class that represents a 'File Cleaner', supporting
    /// a Run method for processing and cleaning desktop files.
    /// </summary>
    public class FileCleaner : ICleanerHelper
    {
        #region Private Data Fields

        /// <summary>
        /// Private data field that represents this types processor locator (that
        /// will contain an instance of a class implementing this interface for 
        /// grabbing concrete types to perform operations.
        /// </summary>
        private IProcessorLocator processorLocator;

        #endregion Private Data Fields

        #region Constructor

        /// <summary>
        /// Instantiates a new FileCleaner object; Autofac deals with
        /// the passing of an IProcessorLocator supporting object (or Moq
        /// handles this when Unit Tests are involved).
        /// </summary>
        /// <param name="locator">An IProcessorLocator implementing object (for this class to support various forms of functionality).</param>
        public FileCleaner(IProcessorLocator locator)
        {
            processorLocator = locator;
        }

        #endregion Constructor

        #region Public Methods

        /// <summary>
        /// Public method that performs the core operation of this class. We obtain 
        /// information from the app.config, retrieve files from the designated desktop
        /// location and process them (i.e. copy to a set location and delete the originals).
        /// </summary>
        /// <returns>A boolean that denotes if this operation completed successfully.</returns>
        public bool Run()
        {
            Console.WriteLine("Running the cleaner helper!");

            // Use this instances IProcessLocator supporting object to get instances of classes supporting the IConfigurationHelper and IFileHelper interfaces
            // for retrieving files and subsequently processing them
            IConfigurationHelper configurationHelper = processorLocator.GetProcessor<IConfigurationHelper>();
            IFileHelper fileHelper = processorLocator.GetProcessor<IFileHelper>();

#if DEBUG
            // In debug, performing a little extra output logging to illustrate object setup (The IConfigurationHelper implementing object is set up as 'Single Instance', so we want to illustrate this)
            CompareObjectsInDebug(configurationHelper, fileHelper);
#endif

            // We have our objects, now run the 'process' and see if it completes successfully
            bool operationSuccessful = false;

            try
            {
                operationSuccessful = fileHelper.ProcessFiles(fileHelper.GetFilesForPathAsList(configurationHelper.GetConfigurationSetting(Application.DesktopAppSettingKey)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return operationSuccessful;
        }

        #endregion Public Methods

        #region Private Helper Methods

        /// <summary>
        /// Private helper method that does a little bit of extra object
        /// interrogation and output, in debug mode, to show object configuration.
        /// </summary>
        /// <param name="configurationHelper">The IConfigurationHelper object passed from the caller (for comparison).</param>
        /// <param name="fileHelper">The IFileHelper object passed from the caller (for comparison).</param>
        private void CompareObjectsInDebug(IConfigurationHelper configurationHelper, IFileHelper fileHelper)
        {
            Console.WriteLine();

            // Create two new objects using the process locator - We want to see if the IConfigurationHelper supporting object is Single Instance, as opposed to the IFileHelper supporting object
            IConfigurationHelper configurationHelper2 = processorLocator.GetProcessor<IConfigurationHelper>();
            IFileHelper fileHelper2 = processorLocator.GetProcessor<IFileHelper>();

            // What are dealing with (additional debug info only) - Actual do the object interrogation; first on Hash Codes
            Console.WriteLine("configurationHelper HashCode: {0}", configurationHelper.GetHashCode());
            Console.WriteLine("configurationHelper2 HashCode: {0}", configurationHelper2.GetHashCode());
            Console.WriteLine("fileHelper HashCode: {0}", fileHelper.GetHashCode());
            Console.WriteLine("fileHelper HashCode: {0}", fileHelper2.GetHashCode());

            // ...Then on an actual 'equals' check
            Console.WriteLine("configurationHelper == ConfigurationHelper2: {0}", configurationHelper == configurationHelper2);
            Console.WriteLine("fileHelper == fileHelper2: {0}", fileHelper == fileHelper2);

            Console.WriteLine();
        }

        #endregion Private Helper Methods
    }
}

The next class, apart from being an example of very, very incomplete exception handling (gulp!) shows a similar pattern to the above class again. The IProcessorLocator object is passed in, as a dependency, to this object’s constructor (when it is resolved and retrieved by an object that requires it) and then utilised to retrieve types to perform the relevant class functions as needed.

This is essentially the workhorse class, handling files, performing the move and delete operations and then reporting the result (in the form of a boolean) to the caller. I’ve utilised a couple of private helper methods, just as processing aids (which could be changed as required/exposed also as public implementations to be overridden).

using DesktopCleaner.Helpers;
using DesktopCleaner.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DesktopCleaner.Implementations
{
    /// <summary>
    /// Public class that represents a 'File Helper', supporting
    /// various methods for obtaining files and cleaning directories.
    /// </summary>
    public class FileHelper : IFileHelper
    {
        #region Private Data Fields

        /// <summary>
        /// Private data field that represents this types processor locator (that
        /// will contain an instance of a class implementing this interface for 
        /// grabbing concrete types to perform operations.
        /// </summary>
        private IProcessorLocator processorLocator;

        #endregion Private Data Fields

        #region Constructor

        /// <summary>
        /// Instantiates a new FileHelper object; Autofac deals with
        /// the passing of an IProcessorLocator supporting object (or Moq
        /// handles this when Unit Tests are involved).
        /// </summary>
        /// <param name="locator">An IProcessorLocator implementing object (for this class to support various forms of functionality).</param>
        public FileHelper(IProcessorLocator locator)
        {
            processorLocator = locator;
        }

        #endregion Constructor

        #region Public Methods

        /// <summary>
        /// Public method that, based on a provided path, will return
        /// files in the given directory in the form of a List<string>.
        /// </summary>
        /// <param name="path">The path to return files for.</param>
        /// <returns>A list of type string representing files in the given directory.</returns>
        public List<string> GetFilesForPathAsList(string path)
        {
            // Two phases of validation here. Ensure the path provided is set and is valid (treating these as both exceptional circumstances in my scenario, could be debated of course)
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (!Directory.Exists(path))
            {
                throw new InvalidOperationException("GetFilesForPathAsList called with a path that does not resolve to a valid directory");
            }

            // Attempt to set the directoryFileList so the data can be returned to the caller
            List<string> directoryFileList = null;

            try
            {
                directoryFileList = Directory.GetFiles(path).ToList();
            }
            catch (Exception ex)
            {
                // TODO (LOL!) - Log
                Console.WriteLine(ex.Message);
            }
            
            return directoryFileList;
        }

        /// <summary>
        /// Public method that serves as the main work-horse for this class.
        /// We consume a file list and, based on app.config AppSetting pathing information,
        /// decided on where to copy files based on extensions (subsequently deleting them from
        /// the original file location after copy).
        /// </summary>
        /// <param name="fileList">The list of files to operate on.</param>
        /// <returns>A boolean representing if the process was a success (fails on first error in its current form).</returns>
        public bool ProcessFiles(List<string> fileList)
        {
            // Phase one validation only, just ensure the file list is set correct (i.e. not null)
            if (fileList == null)
            {
                throw new ArgumentNullException(nameof(fileList));
            }

            bool filesProcessedSuccessfully = false;

            // Not the greatest here! For illustration only, get a class instance to interrogate app.config AppSettings and use this information to clean the file list data
            try
            {
                IConfigurationHelper configurationHelper = processorLocator.GetProcessor<IConfigurationHelper>();

                List<KeyValuePair<string, string>> appSettings = GetAppSettingsForFileProcessing(configurationHelper);
                CopyAndDeleteFilesBasedOnAppSettings(fileList, appSettings);

                // If we get here then we're successful (by definition that the code didn't error only, of course!)
                filesProcessedSuccessfully = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return filesProcessedSuccessfully;
        }

        #endregion Public Methods

        #region Private Static Helper Methods

        /// <summary>
        /// Private static helper method that uses the provided IConfigurationHelper to 
        /// retrieve AppSettings as a KeyValuePair list (essentially just for convenience).      
        /// /// </summary>
        /// <param name="configurationHelper">The IConfigurationHelper supporting class to retrieve settings based on.</param>
        /// <returns>A list of type KeyValuePair containing the various settings.</returns>
        private static List<KeyValuePair<string, string>> GetAppSettingsForFileProcessing(IConfigurationHelper configurationHelper)
        {
            // Prepare a KeyValuePair list for storing the settings in a more convenient format
            List<KeyValuePair<string, string>> appSettings = new List<KeyValuePair<string, string>>();

            // Using a little linq, get every AppSetting key and value and add it to the appSettings list (ignoring the DesktopAppSettingKey, we don't need this for file processing, so pretty much hard coded for purpose :o) )
            configurationHelper.GetAllConfigurationSettings().AllKeys.Where(appSettingKey => !appSettingKey.Equals(Application.DesktopAppSettingKey, StringComparison.InvariantCultureIgnoreCase)).ToList().ForEach(appSettingKey =>
            {
                appSettings.Add(new KeyValuePair<string, string>(appSettingKey, configurationHelper.GetConfigurationSetting(appSettingKey)));
            });

            // Return the results to the caller
            return appSettings;
        }

        /// <summary>
        /// Private static helper method that consumes a file list and 'settings' to perform
        /// a copy and delete process on each file.
        /// </summary>
        /// <param name="fileList">The files to operate on.</param>
        /// <param name="appSettings">The settings to apply to the files regarding copy and delete processing.</param>
        private static void CopyAndDeleteFilesBasedOnAppSettings(List<string> fileList, List<KeyValuePair<string, string>> appSettings)
        {
            // Loop through each file to process individually (just for illustration)
            string copyLocation = null, fileNameOnly = null;
            fileList.ForEach(file =>
            {
                // Retrieve the file name (only) associated with the path, and log to the console
                fileNameOnly = Path.GetFileName(file);
                Console.WriteLine("Attempting to clean: {0}", fileNameOnly);

                // Retrieve the copy location for this particular file extension, if one is set (again, probably better ways to do this, illustration only)
                copyLocation = appSettings.FirstOrDefault(item => item.Key.Equals(Path.GetExtension(file).Remove(0, 1), StringComparison.InvariantCultureIgnoreCase)).Value;

                // If we have a location to copy to then attempt to perform the copy (then delete the file afterwards from its original location). Failure will halt the process
                if (!string.IsNullOrWhiteSpace(copyLocation))
                {
                    File.Copy(file, Path.Combine(copyLocation, fileNameOnly));
                    File.Delete(file);
                }
            });
        }

        #endregion Private Static Helper Methods
    }
}

Lastly, here is the (very, very simple as it turns out!) wrapper for our DI Container, the ProcessorLocator (implementing IProcessorLocator).

using Autofac;
using DesktopCleaner.Helpers;
using DesktopCleaner.Interfaces;

namespace DesktopCleaner.Locators
{
    /// <summary>
    /// Public class that represents a 'Processor Locator', which
    /// just obtains concrete class based on the DI Container in the Program
    /// class (held statically in the DesktopCleaner.Helpers.Application class, which
    /// is set up when this application is started).
    /// </summary>
    public class ProcessorLocator : IProcessorLocator
    {
        #region Public Expression Bodied Methods

        /// <summary>
        /// Based on T provide a concrete class implementation
        /// (that matches the interface in the DI Container).
        /// </summary>
        /// <typeparam name="T">The interface to get a concrete type based on.</typeparam>
        /// <returns>An instance of the concrete class, as mapped.</returns>
        public T GetProcessor<T>() => Application.Container.Resolve<T>();

        #endregion Public Expression Bodied Methods
    }
}

Just for kicks! For anyone wondering what is found in the app.config, here it is for reference:

<!--App Setting Configuration example (within the app.config)-->
<appSettings>
  <add key="DesktopPath" value="C:\Users\fakeuser\Desktop\Imaginary_Desktop"/>
  <add key="jpg" value="C:\Users\fakeuser\Desktop\Imaginary_Desktop\jpeg_folder"/>
  <add key="url" value="C:\Users\fakeuser\Desktop\Imaginary_Desktop\url_folder"/>
  <add key="txt" value="C:\Users\fakeuser\Desktop\Imaginary_Desktop\txt_folder"/>
  <add key="xlsx" value="C:\Users\fakeuser\Desktop\Imaginary_Desktop\xslx_folder"/>      
</appSettings>

Another reference piece just to finish up before we inspect the actual output; a class diagram for the application as it stands (pretty flat and easy to understand):

Desktop Cleaner class diagram showing application structure.

Desktop Cleaner Class Diagram.

So, what do you get when you run this application? The next screenshot should hopefully give a good indication as to what is going on ‘under the hood’.

Here’s the final output, with the most interesting portion of output being in the first section, showing some details about the objects retrieved from the DI Container (using the ProcessorLocator class). This shows that IFileHelper instances (FileHelper in this case) are retrieved as new instances, whereby the IConfigurationHelper instances are single instances as expected (as per the DI Container configuration):

Console output from the Desktop Cleaner application.

Desktop Cleaner Report.

We now have a rough sample of loosely coupled code without concrete implementations embedded. Let’s have a look at the implications for unit testing.

DI and Unit Testing (Moq)

Does this methodology actually help during a basic unit testing scenario? I’ll be using Moq to find out:

Autofac.Extras.Moq NuGet Gallery Reference

In this example, we (after doing a little bit of setting up) utilise the AutoMock.GetLoose (get automatic mocks using loose mocking behaviour) method to retrieve a type to generate our ‘systems under test’ (i.e. other classes). The coolest thing here is that, as demonstrated by the FileHelperProcessFilesTest method, is the injection of the testMoqConfigurationHelper (which is retrieved when the type under test utilises an IProcessLocator to retrieve an IConfigurationHelper supporting object). This way, we are able to ‘rig’ certain parts of an implementation to focus down our unit tests to only specific areas of business logic, certainly very neat indeed. I’ve included all of the implementation code for reference (all commented to add clarity where required).

More details can be found here for those who want to delve a little deeper in Moq:

Moq Documentation

using Autofac.Extras.Moq;
using DesktopCleaner.Implementations;
using DesktopCleaner.Interfaces;
using DesktopCleaner.UnitTests.Helpers;
using DesktopCleaner.UnitTests.MoqObject;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DesktopCleaner.UnitTests
{
    /// <summary>
    /// Public class that holds all of the Unit Test logic to
    /// run Moq tests against the DesktopCleaner application.
    /// </summary>
    [TestClass]
    public class DesktopCleanerTests
    {
        #region Private Static Data Fields (For Unit Tests)

        /// <summary>
        /// Private data fields that represent paths for directories
        /// to used during these unit tests (purely for demonstration).
        /// </summary>
        private static string testDesktopPath = Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder),
            testTxtFilesPath = Path.Combine(testDesktopPath, SharedTestValues.TestTxtFilesFolder),
            testSqlFilesPath = Path.Combine(testDesktopPath, SharedTestValues.TestSqlFilesFolder);

        #endregion Private Static Data Fields (For Unit Tests)

        #region Test Class Initialisation Logic

        /// <summary>
        /// Public method that sets up the required resources for all
        /// of the Unit Tests featured in this class. NOTE: There is a requirement 
        /// for all of the tests to run (you wouldn't want to introduce a 'link' between all
        /// of your tests in production, but as I'm doing a demo this is permissible for now).
        /// </summary>
        /// <param name="context">The TestContext object for this class.</param>
        [ClassInitialize]
        public static void ConfigureTestResources(TestContext context)
        {
            // Create a Test Desktop folder and a TXT/SQL folder as sub-directories (ready to receive content in the tests below)
            Directory.CreateDirectory(testDesktopPath);
            Directory.CreateDirectory(testTxtFilesPath);
            Directory.CreateDirectory(testSqlFilesPath);

            // Add four tests files, two SQL files and two standard TXT file, into the root directory (for 'cleaning' during the unit tests)
            File.Create(Path.Combine(testDesktopPath, SharedTestValues.TestTxtFileNameOne)).Close();
            File.Create(Path.Combine(testDesktopPath, SharedTestValues.TestTxtFileNameTwo)).Close();
            File.Create(Path.Combine(testDesktopPath, SharedTestValues.TestSqlFileNameOne)).Close();
            File.Create(Path.Combine(testDesktopPath, SharedTestValues.TestSqlFileNameTwo)).Close();
        }

        #endregion Test Class Initialisation Logic

        #region Public Static Test Methods

        /// <summary>
        /// Public test method that runs an implementation test against
        /// a FileHelper class and the GetFilesForPathAsList method.
        /// </summary>
        [TestMethod]
        public void FileHelperGetFilesForPathAsListTest()
        {
            using (AutoMock mock = AutoMock.GetLoose())
            {
                // Arrange (i.e. configure the mock)
                FileHelper sut = mock.Create<FileHelper>();

                // Act
                List<string> directoryList = sut.GetFilesForPathAsList(new MoqConfigurationHelper().GetConfigurationSetting(SharedTestValues.DesktopTestAppSettingKey));

                // Assert
                Assert.AreEqual(4, directoryList.Count);
            }
        }

        /// <summary>
        /// Public test method that runs an implementation tests against
        /// a FileHelper class and the ProcessFiles method primarily (ensuring that 
        /// the FileHelper receives a 'mock' version of an IConfigurationHelper for 
        /// testing purposes, which returns a predefined configuration to test against).
        /// </summary>
        [TestMethod]
        public void FileHelperProcessFilesTest()
        {
            using (AutoMock mock = AutoMock.GetLoose())
            {
                // Arrange (i.e. configure the mock)
                MoqConfigurationHelper testMoqConfigurationHelper = new MoqConfigurationHelper();

                // This is the interesting bit - Pass the MoqConfigurationHelper as our implementation of IConfigurationHelper. This turns up in the constructor of our FileHelper (for use in the Unit Test)
                mock.Mock<IProcessorLocator>().Setup(loc => loc.GetProcessor<IConfigurationHelper>()).Returns(testMoqConfigurationHelper);
                FileHelper sut = mock.Create<FileHelper>();

                // Act
                List<string> directoryList = sut.GetFilesForPathAsList(testMoqConfigurationHelper.GetConfigurationSetting(SharedTestValues.DesktopTestAppSettingKey));

                // Assert
                Assert.IsTrue(sut.ProcessFiles(directoryList));
                Assert.IsFalse(Directory.GetFiles(testTxtFilesPath).Any(file => !Path.GetExtension(file).Equals(".txt")));
                Assert.IsFalse(Directory.GetFiles(testSqlFilesPath).Any(file => !Path.GetExtension(file).Equals(".sql")));
            }
        }

        #endregion Public Static Test Methods

        #region Test Class Cleanup Logic

        /// <summary>
        ///  
        /// </summary>
        [ClassCleanup]
        public static void CleanupTestResources()
        {
            // Remove traces of test files, for our next run (as this is all plonked in the debug/bin folder, not what you'd want for a genuine test setup most likely)
            Directory.GetFiles(testTxtFilesPath).ToList().ForEach
                (
                    file => 
                    {
                        File.Delete(file);
                    }
                );

            Directory.GetFiles(testSqlFilesPath).ToList().ForEach
                (
                    file => 
                    {
                        File.Delete(file);
                    }
                );

            Directory.GetFiles(testDesktopPath).ToList().ForEach
                (
                    file => 
                    {
                        File.Delete(file);
                    }
                );

            // Remove any test directories created for any run Unit Tests
            Directory.Delete(Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder, SharedTestValues.TestTxtFilesFolder));
            Directory.Delete(Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder, SharedTestValues.TestSqlFilesFolder));
            Directory.Delete(Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder));
        }

        #endregion Test Class Cleanup Logic
    }
}
using System;
using System.IO;

namespace DesktopCleaner.UnitTests.Helpers
{
    /// <summary>
    /// Public static class that holds all of the 
    /// </summary>
    public static class SharedTestValues
    {
        #region Private Static Data Fields

        /// <summary>
        /// Private static data field that (poorly named really) gets access
        /// to the current directory for this application (for our purposes, during debugging, this
        /// will be the bin/debug folder, for demonstration only).
        /// </summary>
        private static Lazy<string> debugPath = new Lazy<string>(() => Directory.GetCurrentDirectory());

        #endregion Private Static Data Fields

        #region Public Constants

        /// <summary>
        /// Public constant that denotes the desktop path
        /// mock up AppSetting key (not actually real, faked
        /// by our MoqConfigurationHelper).
        /// </summary>
        public const string DesktopTestAppSettingKey = "DesktopPath";

        /// <summary>
        /// Public constant that denotes the desktop folder name 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestDesktopFolder = "Test_Desktop";

        /// <summary>
        /// Public constant that denotes the text file folder name 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestTxtFilesFolder = "Txt_Files";

        /// <summary>
        /// Public constant that denotes the sql file folder name 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestSqlFilesFolder = "Sql_Files";

        /// <summary>
        /// Public constant that denotes the name of the first, test sql file 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestSqlFileNameOne = "Test_Sql_File_One.sql";

        /// <summary>
        /// Public constant that denotes the name of the second, test sql file 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestSqlFileNameTwo = "Test_Sql_File_Two.sql";

        /// <summary>
        /// Public constant that denotes the name of the first, test text file 
        /// to use during Unit Testing.
        /// </summary>
        public const string TestTxtFileNameOne = "Test_Txt_File_One.txt";

        /// <summary>
        /// Public constant that denotes the name of the second, test text file 
        /// to use during Unit Testing. 
        /// </summary>
        public const string TestTxtFileNameTwo = "Test_Txt_File_Two.txt";

        #endregion Public Constants

        #region Public Static Properties

        /// <summary>
        /// Gets access (static) to the lazy debugPath.value.
        /// </summary>
        public static string DebugPath
        {
            get
            {
                return debugPath.Value;
            }
        }

        #endregion Public Static Properties
    }
}
using DesktopCleaner.Interfaces;
using DesktopCleaner.UnitTests.Helpers;
using System.Collections.Specialized;
using System.IO;
using System.Linq;

namespace DesktopCleaner.UnitTests.MoqObject
{
    /// <summary>
    /// MoqConfigurationHelper class to provide a specific implementation of an
    /// IConfigurationHelper just for Unit Testing (not necessarily how best to structure
    /// a class, just for illustration purposes only).
    /// </summary>
    public class MoqConfigurationHelper : IConfigurationHelper
    {
        #region Private Static Data Fields

        /// <summary>
        /// Private static data field that represents a mock
        /// set of Application Settings for use during Unit Testing.
        /// </summary>
        private static NameValueCollection testAppSettingsCollection = null;

        #endregion Private Static Data Fields

        #region Constructor

        /// <summary>
        /// Initialises a new instance of a MoqConfigurationHelper.
        /// </summary>
        public MoqConfigurationHelper()
        {
            // THIS COULD, OF COURSE, BE STORED IN AN APP.CONFIG ALSO AS PART OF THIS PROJECT, BUT I WANT TO DEMONSTRATE A FULL MOCK UP HERE AND FANCY DOING A BIT MORE HARD WORK!

            // Set testAppSetingsCollection to be a new NameValueCollection
            testAppSettingsCollection = new NameValueCollection();

            // Create three, mock 'AppSettings' denoting a desktop, sql and text files path (to be used during Unit Tests)
            testAppSettingsCollection.Add(SharedTestValues.DesktopTestAppSettingKey, Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder));
            testAppSettingsCollection.Add("Sql", Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder, SharedTestValues.TestSqlFilesFolder));
            testAppSettingsCollection.Add("Txt", Path.Combine(SharedTestValues.DebugPath, SharedTestValues.TestDesktopFolder, SharedTestValues.TestTxtFilesFolder));
        }

        #endregion Constructor

        #region Public Expression Bodied Methods

        /// <summary>
        /// Public method that returns all 'AppSettings'
        /// (mock only) to the caller.
        /// </summary>
        /// <returns></returns>
        public NameValueCollection GetAllConfigurationSettings() => testAppSettingsCollection;

        /// <summary>
        /// Public method that returns a specified AppSetting
        /// to the caller based on key (mock only).
        /// </summary>
        /// <param name="key">The unique key for the value to be retrieved.</param>
        /// <returns>The value corresponding to the unique key.</returns>
        public string GetConfigurationSetting(string key) => testAppSettingsCollection.GetValues(key).FirstOrDefault();

        #endregion Public Expression Bodied Methods
    }
}

Being a stickler for providing full details, here is the class diagram for the Unit Test project:

Desktop Cleaner unit test project class diagram illustrating structure.

Desktop Cleaner Unit Test Project Class Diagram.

As a final thought, here’s a little bit of proof captured at runtime showing the different concrete implementations retrieved when hitting a breakpoint during debug of the application running in and out of a unit testing scenario:

Illustration showing the IConfigurationHelper object type during debug.

IConfigurationHelper Object Type During Debug.

Illustration showing the IConfigurationHelper object type during unit testing.

IConfigurationHelper Object Type During Unit Testing.

Since generating content for this post I’ve had more thoughts and ideas surrounding DI in general, something that seems to make a follow-up post a worthy thing to pursue! I’d like to flesh these examples out at the very least, so watch this space for more on this subject.

Thanks again all, until the next time…

One thought on “When are Injections Fun? C# Dependency Injection Deep Dive

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s