Thoughts on DDD and IoC

I have found that, if you drive out the dependencies of an object and express those dependencies in terms of interfaces, your domain tends to be a lot more clearly defined but that you need to rely far more heavily on your IoC container to address these dependencies. Fortunately, it also allows you to find dependency patterns far more easily and consolidate those dependencies into concrete implementations that have a focus in purpose (a.k.a. the single responsibility principle). Driving out these dependencies from the requirements of the class through interfaces leads to many small, client-specific, interfaces so that anyone that comes across the class later on and wants to try and figure out what the intent is of the code is not going to be distracted by a dependency that has been passed in that has many more methods on it than is needed by the client class itself (a.k.a. the interface segregation principle). Making these dependencies required through either constructor dependency (my personal choix de vie) or property dependency injection (not my favourite because it is more open to runtime errors) is called an inversion of control (a.k.a. the dependency inversion principle)  leads to strong reliance on an Inversion of Control container.  This method of designing classes and driving out features are two of the three principles of SOLID design.

SOLID is not new (thank you Uncle Bob!) and I think that many of the concepts are generally agreed upon by most developers concerned with good design. What I want to do in this article is try and illustrate how this changes the way you develop your code.

In the first scenario, I am responsible for building a class that shows the name of the application in the title bar of the application window. We’re trying to develop a really strong architecture with as few points of failure as possible so that we can make a change in one spot and it corrects the bug in other spots as well.

  • Whether I am using MVP, MVC, MVVM, or straight code-behind classes I’ll have a class that is connected to the User Interface screen (webpage, windows form, mobile device screen, whatever).

class MainPageBackingClass {
        // Public property the UI uses to provide the Application Name in the title bar
        public string TItleBarText { get { } }

  • There’s a desire to provide localization for our application and that’s going to be provided somewhere else in our application. My class needs to get the string that puts the application name up on the screen.

class MainPageBackingClass {
        public MainPageBackingClass(IMainPageBackingClassStringsProvider stringsProvider) { .. }
        // Public property the UI uses to provide the Application Name in the title bar
        public string TItleBarText { get { return  stringsProvider.ApplicationName; } }

interface IMainPageBackingClassStringsProvider { string ApplicationName { get; } }

At this point I don’t care, from the design of my class’ perspective, what is implementing IMainPageBackingClassStringsProvider, I just care that I need something to provide that string for me. The subtle point to notice here is that the class is defining what it needs and driving out it’s dependencies. There is an interface (IMainPageBackingClassStringsProvider) that is providing only the single string. That’s okay.

Okay, I’m done and I feel good about myself. My next assignment is to create a class that assembles an email message. It puts the user’s name in the formatted message.

  • I need a class that takes a format-able string and puts the user’s name in it.
class MessageBuilder { }

  • It’s going to need something to provide the formatted message to it.
class MessageBuilder {
        MessageBuilder(IFormattedMessageProvider messageProvider) { … }

interface IFormattedMessageProvider { string FormattedMessage { get; } }

  • And now a method that takes in something that provides the user’s name
class MessageBuilder {
        public string Format(IUserNameProvider userNameProvider) {
               return string.Format(messageProvider.FormattedMessage, userNameProvider.UserName);

interface IUserNameProvider { string UserName { get; } }

In my application I now have three dependencies (IMainPageBackingClassStringsProvider, IFormattedMessageProvider, and IUserNameProvider). There’s an emerging pattern here that there are at least two dependencies requiring strings. Since a class can implement multiple interfaces without any problem, I am going to build a class that has a singular purpose (to provide localized strings) and implement both interfaces.

class StringsProvider : IMainPageBackingClassStringsProvider, IFormattedMessageProvider {
         public string ApplicationName { get { return “Hello World”; } }
         public string FormattedMessage { get { return “Welcome {0}!”; } }

Now, here’s the kicker of this entire scenario. There’s a temptation for us to consolidate all of those strings that are being provided by the StringsProvider class into a single interface (maybe call it IStringsProvider) and have both the MessageBuilder class and MainPageBackingClass have a dependency on a single interface. On first inspection, that would appear to a good idea. The issue comes that a later developer might get confused as to the intent of the code in one of the classes if there are more methods/properties available to them than is needed by the class. If, for example, it ended up that you had two interfaces, one provided ApplicationName as a string and another providing ApplicationTitle as a string.

From within the context of separate interfaces, each class relying on an interface providing only the single string, it would be easy for the developer to know which string they were to be using within the class. It wouldn’t be confusing because there’s only one property to choose from. If, though, we had consolidated those string providing dependencies into a single interface, we now have two properties (ApplicationName and ApplicationTitle) being provided by this interface. Which one should I, as a developer of MainPageBackingClass choose? What if there are hundreds of other properties to choose from in my consolidated interface that I now have to scan through and guess which one I really need to use? It’s much easier to express the intent of the code through individualized interfaces.

Interfaces are the cheapest thing to produce in code.

Luckily classes can implement multiple interfaces (even hundreds if need be) and there’s always your IoC container that can produce all the magic to get your class the one it needs at run-time.

Local Installation of Windows Server AppFabric

I went through the process of installing and getting AppFabric working on my local machine based on information I gathered in my Windows Workflow 4.0 and Windows Server AppFabric – My Resources for Getting Started post. I then had to create a document that instructed other developers on my team how to install and get our workflow app up and running. Here’s the script (as I think it would be useful to anyone else just getting started). I know that not all the steps are necessary (e.g. installation of the persistence store can be done within the AppFabric Configuration Wizard) but I felt these were the more intuitive steps to letting developers know what was going on under the hood. Here goes nothing:

Installing AppFabric

  1. Download and install the version of Windows Server AppFabric appropriate for your machine (see Additional Information section at bottom of the page to determine which to install)

Note: At the end of installation you will see the “See recommended updates” link at the top. Click it and install the updates. Also, uncheck the “Launch configuration tool.” checkbox. We will configure this in a separate step to add clarity.

Make sure you do this!

Installing Persistence Store (Database)

  1. Create a new database (“SQLPersistenceStore”, but name is really unimportant), run the scripts (provided by Microsoft) to create the schema and logic for this database. Manually run the following scripts, located in %SystemRoot%\WINDOWS\Microsoft.Net\Framework\v4.0.30319\SQL\en\ or %SystemRoot%\WINDOWS\Microsoft.Net\Framework64\v4.0.30319\ if you are running a 64 bit operating system: SqlWorkflowInstanceStoreSchema.sql and SqlWorkflowInstanceStoreLogic.sql
  2. Create a SQL User account to connect to the newly created database. The user account needs to have db_reader and db_writer permissions as well as be given ownership of the System.Activities.DurableInstancing schema (created in the above step).

Configuring AppFabric

  1. Run the Configure AppFabric application (now installed in your start menu).
    Do this too!
  2. (Optional? I am not sure that the monitoring service is necessary but I think that it is what creates the add-in in IIS Manager to view the persisted instances) On the ‘Hosting Services Tab’ of the Windows Server AppFabric Configuration Wizard’ screen, check the ‘Set monitoring configuration’ checkbox, select the System.Data.SqlClient item from the ‘Monitoring provider’ drop-down and click ‘Configure’
    Configuring the Hosting Service
  3. On the ‘Windows Server AppFabric Monitoring Store Configuration’ screen, click the ‘Register AppFabric monitoring store in root web.config checkbox, select the database (created in step 1 above) in the Connection String section, and select the ‘SQL Server authentication’ option in the ‘Security Configuration’ section, providing the username and password created above.
    Configuring the Monitoring Store
  4. Back on the Hosting Services Tab, check the ‘Set persistence configuration’ checkbox, select the sqlStoreProvider item from the ‘Persistence provider’ drop-down and click ‘Configure’
    Configuring the Persistence Store
  5. On the ‘Windows Server AppFabric Persistence Store Configuration’ screen, click the ‘Register AppFabric persistence store in root web.config checkbox, select the database (created in step 1 above) in the Connection String section, and select the ‘SQL Server authentication’ option in the ‘Security Configuration’ section, providing the username and password created above.
  6. Back on the ‘Windows Server AppFabric Configuration Wizard’, click the ‘Next >’ button to complete the wizard.

Creating the Virtual Directory

  1. Open IIS Manager (inetmgr from the ‘Run’ prompt) and create a new Application under the Default Website node and pointing the virtual directory to the workflow project folder in your development environment (e.g. c:\dev\MyWorkflowApp\source\application\WorkflowProject).

Windows Workflow 4.0 and Windows Server AppFabric – My Resources for Getting Started

I’m starting on a new feature of the application I work on in my day-to-day. We’re building out a feature to replicate some human workflows that are long running. Here’s some of the resources I have accumulated so far:


Windows Workflow Foundation (WF) is a method of creating discrete activities that can be used to model the workflow of an application or human workflows. It “provides a programming model, in-process workflow engine and rehostable designer to implement long-running processes as workflows within .NET applications”.

With .NET 4.0, a new programming model as well as further integration between Windows Communication Foundation (WCF) and WF was created.

The tasks I am looking to automate are human activities that are often long-running such as follow-up processes as well as approval processes where an activity is performed, a duration expires or the workflow is preempted by further user input and then continues to completion. The Creating a Long-running Workflow Service article defines a durable workflow as a “long running workflow services may run for long periods of time. At some point the workflow may go idle waiting for some additional information. When this occurs the workflow is persisted to a SQL Server database and is removed from memory. When the additional information becomes available the workflow instance is loaded back into memory and continues executing.” These long running, durable workflows can be hosted in WCF Services (Hosting Options: self-hosted in a managed application, hosted in a managed windows service, in Internet Information Services [IIS], or Windows Process Activation Services [WAS]), Windows Servies (self-created or Windows Server AppFabric), or in the cloud (Windows Azure AppFabric).

WF 4.0

Activity-specific Links

Windows Server AppFabric



Windows Workflow (WF) Samples

Download Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4


See Also

A small change

This is a small tid-bit of an extension method I created when I realized that the ability to combine a collection of strings into a character-separated string was only available as a static method of the String class:

public static string Join(this IEnumerable<string> strings, string separator) {
    return String.Join(separator, strings);

This allows me to achieve the following, which I would argue is slightly more intuitive:

var myListOfStrings = new List<string> {"January", "February", "March"};
var myCombinedListOfString = myListOfStrings.Join(",");

Planning an Iteration – The Story Breakdown Discussion

In a previous post I had mentioned the use of Fibonacci numbers to estimate the tasks. During a discussion between developers, testers and the stakeholder, stories are broken down into a series of understood development tasks. Each of the tasks is then estimated based on relative complexity. At this point I imagine being asked "How far should you break down a story?" to which I would reply that it depends solely on the comfort level of the developers to know what’s involved in completing the story. I would suspect that early on in a project, when there is a lot of unknown technical details on how a story is to be implemented, a lot of small tasks would be created. As the number of unknown technical details decreases, I would suspect it would lead to teams to generalize tasks a little more. The end result is the same. The tasks involved in completing a story are defined and estimated. The take-away from this discussion is to give the stakeholder the ability to know more about the difficulty of implementing a story and giving them the ability to make more educated decisions when deciding what stories they would like to have in the upcoming iteration.

One thing to note is that the domain of agility withing Agile Methodology is not simply the domain of the developer. It is certainly within the realm of possibility that, as the discussion ensues, the story breaks out a number of other stories becomes an epic and is further broken down into a series of other stories. This is where, I believe, the art and beauty of the Agile comes into play. That we are all imperfect but all working toward a common goal of making something to improve acknowledges the humanity of all involved in the process and truly does improve each person involved.

Extending interfaces that you don’t control

An example of an interface that you don’t control can be the service client generated by a WCF service reference. If your service contract and operations are defined in an interface, the generated proxy creates the interface and a class generally called <ServiceName>Client. You can make your calls to the service, but if you don’t call the Close method, you’ll find yourself in a faulted state sooner or later.

A simple way to allow you to isolate your dependency on the ClientBase(TChannel).Close Method is to extend the service interface and add the Close method:

public interface IServiceClientBuilder {
    IService Create();
public class ServiceClientBuilder : IServiceClietBuilder {
    public IService Create() {
        return new ServiceClient();
public static class ServiceInterfaceExtensions {
    public static void Close(this IService client)  {
public class MyConsumer {
     IServiceClientBuilder clientBuilder;
     public MyConsumer(IServiceClientBuilder clientBuilder) {
         this.clientBuilder = clientBuilder;
    public void DoSomething() {
        var client = clientBuilder.Create();
        // client.SomeMethod()

This minimizes the "difficult to test" code to only the single-line extension method.

Using Linq to enhance (?) readibility

I am not certain if this is a valid example of a fluent interface, but I thought I would post it as I found it a reasonably interesting way to remove checks for != null or == null from code to make it "read" better. This example creates an extension method using Linq to extend reference objects.
public static class Utility {
     public static bool IsNotNull<T>(this T item) where T : class {
          return item != null;
     public static bool IsNull<T>(this T item) where T : class {
          return item == null;

You can, then, write checks to be like this for any reference object:
if(obj.IsNotNull())  {

As I said, I am not certain if this is truly a "fluent interface", but can (arguably) make the code read easier.

5 Things you likely don’t (never wanted to?) know about me

 I have been tagged. Here’s 5 things you may not already know about me.
  1. I have 4 mothers.
  2. I love most breeds of dog but don’t want one for my own.
  3. I have received compensation (in the form of both drinks purchased by strangers as well as one-time, gainful employment) for my karaoke "skillz", though the last time I was at karaoke was January 1, 2005.
  4. I prefer to be a passenger in a vehicle.
  5. Though not likely a surprise (being that I am from Edmonton), Wayne Gretzky is the sports figure I most respect. The closest I can claim to having met him is that I once caught a puck, tossed to me during the pre-game warm-up of the 40th NHL All-Star Game. I was standing on the dasher-boards with one hand holding onto the glass. The other hand dropped the puck. Mr. Gretzky never saw me drop the puck and gave it away to someone else. Though disappointing to not have that momento, it is still a special memory.

I don’t think I know 5 bloggers who haven’t already been tagged, so I’ll leave it with me. Suggestions welcomed.