Roll Your Own COP. Part I: Mixins

A new programming paradigm has been born in distant land of Java. Qi4j introduces the first Composite Oriented Programming (COP) concept to the world, and has drawn massive interest among Java crowd ever since.
It drove me to start a work on implementing Composite Orientation on .Net as a project named Composheep. This will be an open-source lightweight COP framework (as defined by Qi4j) that I will build incrementally as I write each step on this blog as “Roll Your Own COP” series. I publish the project in CodePlex as LGPL.
Let’s start from the mission of COP. One of the biggest flaws of OOP is that it’s not object oriented at all. If anything, OOP is Class-Oriented, since class is the primary citizen that all objects are derived from. Not the other way round.
As an example, I am a programmer at work, a driver in a car, a researcher in kitchen, and a hunter and a pray in the jungle. As an object, my role (class) constantly changes depending on contexts. Some objects also traverses different scope boundaries. For instance, a Person will have its classes changing over time. New abilities are learnt, from Kid, Student, Dancer, Ninja, and he will eventually due, but it doesn’t mean that the Person object should be deleted from the system since the “memory” of him may live for long time. In a conventional OOP system, we will need to transfer some of the states across instances of different classes. In Composite Oriented Programming, they are all ONE instance. We assign role (Class) to an object. Not instantiating objects based on a destined class. Object is therefore the primary citizen of COP. Please visit Qi4j site for more detail.
One of the most important COP concepts is mixin, in which multiple reusable classes are mixed to form a solid composite. It relies much on Java class generation technique, in which .net is always known far inferior. But, as the first part of the series, I will show how easy it actually is to build our own Mixins implementation on .net using Castle DynamicProxy, in only 15 minutes.
Our objective is to achieve a robust Mixins builder that is smart enough to:
– Handle both properties and methods
– Differentiate parameters overload. E.g. foo() and foo(string)
– Handle generic methods. E.g. foo<T>()
– Differentiate generics overload. E.g. foo<T>() and foo<T,Y>()
– Declarative programming using attributes
As a sample use-case, first I will define a composite of Person that is composed from 2 mixins: HasName and CanFight. I want to define the composite in the following fashion:

[Mixin(typeof(HasNameImpl), typeof(Fighter))]
public interface Person: HasName, CanFight
{
}

Note that Person, as a composite, is defined as an interface. We won’t write any implementation of Person since it will be automatically derived by composing 2 mixin implementations together. We declaratively specify that we wish to use HasNameImpl and Fighter as mixin implementor by using Mixin attribute.
Here is the definition of the mixins:

public interface HasName
{
	string FirstName{ get; set;}
	string LastName { get; set;}

	string IntroduceSelf();
	string IntroduceSelf(string target);
}

public interface CanFight
{
	string Kick<Target>();
	string Kick<LTarget, RTarget>();
}

And the following is the implementation of each mixins:

public class HasNameImpl: HasName
{
	public string FirstName {get; set;}
	public string LastName {get; set;}

	public string IntroduceSelf()
	{
		return Console.Writeln(
			"Hi there, I am {0} {1}",
			FirstName, LastName);
	}

	public string IntroduceSelf(string target)
	{
		return Console.Writeln(
			"Hi {0}, I am {1} {2}",
			target, FirstName, LastName);
	}
}

public class Fighter: CanFight
{
	public string Kick<Target>()
	{
		return Console.Writeln
			("Roundhouse kick to {0}",
		typeof (Target).Name);
	}

	public string Kick<LTarget, RTarget>()
	{
		return Console.Writeln
			("Left foot to {0}, and right foot to {1}",
		typeof (LTarget).Name,
		typeof (RTarget).Name);
	}
}

The following is how I want the client code to be:

CompositeBuilder builder = new CompositeBuilder();
Person person = builder.BuildComposite<Person>();

person.FirstName = "Hendry";
person.LastName = "Luk";
person.IntroduceSelf());
person.IntroduceSelf("Goofy"));
person.Kick<Dog>());
person.Kick<Dog, DebtCollector>());

We instantiate an object of Person, whose implementation is generated dynamically by mixing HasNameImpl and Fighter together to form a complete Person. This way, we will be able to separate a class into smaller chunks of fragment (mixin) that can be reused effectively.
I think this use simple use-case provides a good coverage to all our 5 requirements. It exploits the use of properties, methods with overloaded parameters, and methods with overloaded generics.
Now, to make this work, we will need to write the CompositeBuilder as part of our Composheep solution. We will be using Castle DynamicProxy, which is a lightweight proxy generator used in many open-source frameworks like nHibernate, Windsor, Aspect#, etc.
Here is the implementation of CompositeBuilder. It searches for MixinAttributes in supplied type, then grab the mixin implementer types that was provided as attribute parameter.

public class CompositeBuilder
{
	private ProxyGenerator generator = new ProxyGenerator();

	public T BuildComposite<T>() where T : class
	{
		CompositeInterceptor interceptor = new CompositeInterceptor();

		object[] attributes =
		typeof(T).GetCustomAttributes(typeof(MixinAttribute), true);
		foreach (MixinAttribute mixin in attributes)
		{
			foreach (Type mixinType in mixin.Types)
				interceptor.AddMixin(Activator.CreateInstance(mixinType));
		}

		return generator.CreateInterfaceProxyWithoutTarget(interceptor);
	}
}

ProxyGenerator is an API from Castle DynamicProxy that we use to dynamically define implementation of composite interface. The most important part of this only method is that in each mixin type defined in mixin attribute, we use default constructor to instantiate the mixin, and pass it to CompositeInterceptor. It’s a custom proxy interceptor that we will create to handle each composite method invocation to its corresponding mixin implementation.
Here is the code for CompositeInterceptor.

internal class CompositeInterceptor : IInterceptor
{
	Dictionary methodTargetMap =
		new Dictionary();

	public void AddMixin(object mixin)
	{
		Type targetType = mixin.GetType();

		MethodInfo[] methods =
		targetType.GetMethods(
		BindingFlags.Instance |
		BindingFlags.Public |
		BindingFlags.NonPublic);

		foreach(MethodInfo method in methods)
		{
			// Skip members declared in System.Object
			if (method.DeclaringType == typeof(object))
				continue;

			methodTargetMap.Add(method.ToString(), mixin);
		}
	}

	// Implementing IInterceptor.Intercept method
	public void Intercept(IInvocation invocation)
	{
		object target = FindMixin(invocation.Method);
		if (target == null)
			throw (new NotImplementedException());

		invocation.ReturnValue =
		invocation.Method.Invoke(
		target, invocation.Arguments);
	}

	private object FindMixin(MethodInfo callMethod)
	{
		if (callMethod.IsGenericMethod)
			callMethod = callMethod.GetGenericMethodDefinition();

		foreach (String method in methodTargetMap.Keys)
		{
			if (method == callMethod.ToString())

				return methodTargetMap[method];
		}
		return null;
	}
}

The idea is that AddMixin method will map each method signature with a mixin instance in a Dictionary. Therefore, when we intercept a proxy method invocation, we will be able to lookup the dictionary for the method signature, and get the mixin instance. Finally, the invocation will be redirected to that mixin instance.
The easiest way to lookup matching method signature (in FindMixin method) is by using MethodInfo.ToString() since it gives us the method name, parameters types, return type, and generic parameters. So we will be using this as the key of the Dictionary as well.
The only problem with generic parameter is that we will be storing open-generic method signature, for example, string Kick() in AddMethod method during interface introspection. But during invocation, we will get passed with a closed-generic method, for instance, string Kick(). To get around this, we put 2 lines on top of FindMixin:

if (callMethod.IsGenericMethod)
callMethod = callMethod.GetGenericMethodDefinition();

It converts void Kick() back into void Kick(). And this is all we need to build our mixin builder! Run the application, and this is what we got:

Just few minutes of pretty straightforward code and we’ve got the building block for our Composheep in place. You can download the code for this episode here. Coming next, in the second episode, we will be building the second features of COP: concerns and side-effects.

Unit Testing Web UI with Monorail

3 rules that always apply in regard to unit-test:

1.       Do NOT unit-test your infrastructure

2.       Test should be automated without user intervention

3.       Design is easy to test, by human eyes. Not by machines.

Let’s now see how our UI fits into this equation. Firstly, user interface involves a lot of infrastructure. To name a few: Http layers, GDI, session management, control callback, and all kind of web security manners. These things are not within our comfort zone and should not be coupled with our unit-test.

Secondly, there is virtually no way to navigate UI without having your hands on mouse and keyboard. Remember, the first word in UI is “User”.

And last, UI is all about design. The UI elements themselves have little meaning to machines, but it means everything on human perception. You might not even notice few slight changes on UI design, but it’s more than likely to break all automated UI test scripts.

Try unit testing your UI, and you’ll quickly break all those 3 rules. User interface code has seemed to repel all but the most serious attempts at test automation. Therefore, automated testing against UI code was just flat out deemed too much work for the gain.

The equation has changed over the last several years with the emergence of MVC architecture. MVC is UI pattern that improves UI testability.  UI is an ugly untestable part of the application, and using MVC, we want to isolate the ugliness in one place (the View), and put the logic in a place that’s easier to test (the Controller). We will slice the View as thin as possible. Put as little code as possible in the View. Remember, any code in a View is almost automatically harder to test than it would be in a Controller.

Castle Monorail is one of the first MVC alternatives to ASP.Net web-form. It’s based on Ruby on Rails, and brings 2 most important features to Asp.Net: simplicity and separation of concerns. To demonstrate how it can improve web development, I will show an overly simplistic demo application using untestable ASP.Net web form, and demonstrate how easy it is to switch to Monorail counterpart, and make it a fully testable web application.

The application is “The Pester”. It allows users (employees) to login into the system, so their boss can assign them with tasks and keep bugging them for the rest of the day. Hence the application name.

First screen is a pretty basic login screen.

It asks for username and password, authenticate to SecurityService. If fails, display a message the the user. And if authentication passes, it will redirect to “View Task Summary” screen. It’s not that complex of a requirement really. The code behind of the webform:

public partial class login : System.Web.UI.Page

{

   protected void Page_Load(object sender, EventArgs e)

   {

      this.lbLoginFailure.Visible = false;

   }

 

   protected void btLogin_Click(object sender, EventArgs e)

   {

      SecurityService securityService = new SecurityService();

                    

       bool isSuccess = securityService.AuthenticateLogin(

       this.txUsername.Text, this.txPassword.Text);

 

       if(!isSuccess)

          this.lbLoginFailure.Visible = true;

       else

          Response.Redirect(“viewTask.aspx”);

    }

}

That’s pretty self-explanatory. And now the “View Task Summary” screen looks like the following:

 

It starts with a very friendly welcoming message, which is followed by a list of all the tasks for current user fetched from the database. The aspx code:

<%@ Page Language=”C#” AutoEventWireup=”true”

         CodeBehind=”taskSummary.aspx.cs”

         Inherits=”SheepTask.WebForm.viewTask” %>

 

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >

<head runat=”server”>

   <link rel=”stylesheet” href=”css/default.css”

         type=”text/css” />

   <title>Tasks From Pester</title>

</head>

<body>

   <form id=”form1″ runat=”server”>

     <h1>Now Get Back to Work!</h1>

     <asp:DataGrid id=”dgTasks”

       HeaderStyle-CssClass=”gridHeader” CssClass=”grid”

       runat=”server” AutoGenerateColumns=”False”>

       <Columns>

          <asp:BoundColumn ItemStyle-Width=”100″

              DataField=”SlaDate” HeaderText=”SLA”

              DataFormatString=”{0:dd/MM/yyyy}” />

          <asp:BoundColumn ItemStyle-Width=”120″

              DataField=”AssignerName” HeaderText=”Assigner” />

          <asp:HyperLinkColumn ItemStyleWidth=”500″

              DataNavigateUrlField=”TaskID”

              DataNavigateUrlFormatString=

                     “taskDetail.aspx?taskId={0}”

              DataTextField=”Title” HeaderText=”Task”/>

       </Columns>

     </asp:DataGrid>

   </form>

</body>

</html>

And the code behind of the webform:

public partial class viewTask : System.Web.UI.Page

{

   protected void Page_Load(object sender, EventArgs e)

   {

      string username = (string)Session[“username”];

      TaskRepository taskRepository = new TaskRepository();

      IList<Task> tasks =

           taskRepository.GetAllTasks(username);

             

      this.dgTasks.DataSource = tasks;

      this.dgTasks.DataBind();

   }

}

That code really isn’t that complex, but let’s think about how we could automate a test for this requirement to run within our regression test suite. That little bitty coupling with web control and coupling to HttpResponse that results is a serious pain to deal with in an automated test. Furthermore, the dependency with SecurityService and TaskRepository makes it impossible to be unit-tested in isolation to backing LDAP and database. But I think the worst part is that to test this logic you have to fire up the browser, navigate through login page, then trigger the btnLogin Click event. That’s a lot of work just to get to the point at which you are exercising the code you care about.

Now, let’s rewrite these screens with Monorail. The structure of our Monorail project looks like the following.

Other than default configuration to activate Monorail in Web.config, we won’t need any more configuration to get this working. This simplicity is one of the main strengths of Monorail that is well borrowed from Rail’s concept of “Convention over Configuration”. In our structure, we have 2 views split across 2 folders: home and task. By convention, the controllers will need to be defined with name HomeController and TaskController, each of which will have a method with a name corresponding to the filename of its respective view template: Login and TaskSummary. Each of the views looks like the following.

<html>

<head>

  <link rel=”stylesheet” href=”/css/default.css”

        type=”text/css” />

  <title>Pester Login</title>

</head>

<body>

<form>

   <% if isLoginFailed: %>

      <div class=”error”>Failed to match username and password</div>

   <% end %>

   Username: <input name=”username” type=”text” /> <br />

   Password: <input name=”password” type=”password” /> <br />

   <input id=”login” value=”Login” type=”submit” />

 </form>

</body>

</html>

 

<html>

<head>

    <link rel=”stylesheet” href=”/css/default.css”

          type=”text/css” />

    <title>Pester Login</title>

</head>

<body>

   <h1>Now Get Back to Work!</h1>

   <table class=”grid”>

     <tr class=”gridHeader”>

        <td width=”100″>SLA</td>

        <td width=”120″>Assigner</td>

        <td width=”500″>Task</td>

      </tr>

      <% for task in taskList: %>

      <tr>

        <td>${task.SlaDate.ToString(“dd/MM/yyyy”)}</td>

        <td>${task.AssignerName}</td>

         <td>

           <a href=”taskDetail.aspx?taskId=${task.TaskId}”>

               ${task.Title}

           </a>

         </td>

      </tr>

      <% end %>

   </table>

</body>

</html>

Now let’s implement the controller for our first page: login. First, to allow the code to be tested without concrete implementation of LDAP SecurityService, we refactor the SecurityService to extract an interface. The following is the code for HomeController.

public class HomeController: SmartDispatcherController

{

   private ISecurityService securityService;

 

   public HomeController(ISecurityService securityService)

   {

       this.securityService = securityService;

   }

 

   public void Login()

   {

       PropertyBag[“isLoginFailed”] = false;

   }

 

   public void Login(string username, string password)

   {

       if (securityService.AuthenticateLogin

             (username, password))

       {

           Session[“username”] = username;

           Response.Redirect(“task”, “taskSummary”);

       }

       else

           PropertyBag[“isLoginFailed”] = true;

   }

}

Notice the ISecurityService. We no longer tie the UI with concrete implementation of SecurityService. This will allow good isolation for our unit-test later on. I also use SmartDispatcherController that gives us a slick feature for automatic data-binding. It automatically transform query string and POST values into method’s parameters with corresponding names. We have therefore 2 overload of Login method: a parameter-less method for initial visit to the login screen, and another method that takes username and password to handle user’s POST login request. The form information will automatically gets passed to both parameters. SecurityService is injected through constructor.

Our second controller follows. There’s nothing special compared to the first controller.

public class TaskController: SmartDispatcherController

{

    private ITaskRepository taskRepository;

 

    public TaskController(ITaskRepository taskRepository)

    {

       this.taskRepository = taskRepository;

    }

 

    public void TaskSummary()

    {

       string username = (string)Session[“username”];

       PropertyBag[“taskList”] =

            taskRepository.GetAllTasks(username);

    }

}

How is this model better? Since I’ve been claiming that this style of structuring the user interface improves the testability of our web, let’s take a look at how we can write our unit-test for login. Astute readers will now note that I should be writting the unit-test code before started the controller code. But it’s a bit hard to explain things in that order. 

[TestFixture]

public class HomeControllerTest : BaseControllerTest

{

   private MockRepository mockery;

   private ISecurityService service;

   private HomeController controller;

 

   [SetUp]

   public void BeforeTest()

   {

      mockery = new MockRepository();

      service = mockery.CreateMock<ISecurityService>();

      controller = new HomeController(service);

      PrepareController(controller);

   }

 

   [Test]

   public void ShouldAlertUserForInvalidLogin()

   {

      using (this.mockery.Record())

      {

         Expect.Call(

            service.AuthenticateLogin(“myUser”, “myPassword”))

            .Return(false);

      }

 

      using (mockery.Playback())

         controller.Login(“myUser”, “myPassword”);

 

      Assert.AreEqual(true,

         controller.PropertyBag[“isLoginFailed”]);

   }

 

   [Test]

   public void SuccessfulLoginShouldRedirectToTaskSummary()

   {

      using (mockery.Record())

      {

         Expect.Call(

            service.AuthenticateLogin(“myUser”, “myPassword”))

            .Return(true);

      }

 

      using (mockery.Playback())

         this.controller.Login(“myUser”, “myPassword”);

 

      Assert.AreEqual(“/task/taskSummary.rails”,

         Response.RedirectedTo);

   }

}

Now you notice that since we have extracted out the interface for SecurityService, we can use Rhino-Mock to mock out the SecurityService implementation from the controller. I use BaseControllerTest from Monorail test-helper to intercept Response and Request object in order to evaluate URL redirection (to /task/taskSummary.rails) without tying the test to web infrastructure. PrepareController is one of the method comes from the BaseControllerTest that does the mock-out for us.

TaskController can be as easily unit tested in similar fashion.

[TestFixture]

public class TaskControllerTest: BaseControllerTest

{

   [Test]

   public void ShouldDisplayUsersTaskSummary()

   {

      MockRepository mockery = new MockRepository();

      ITaskRepository taskRepository =

         mockery.CreateMock<ITaskRepository>();

      TaskController controller = new

         TaskController(taskRepository);

      

      PrepareController(controller);

 

      Context.Session[“username”] = “myUser”;

      List<Task> taskList = new List<Task>();

      

      using(mockery.Record())

      {             

         Expect.Call(taskRepository.GetAllTasks(“myUser”))

            .Return(taskList);

      }

 

      controller.PropertyBag[“tasks”] = taskList;

   }

}

That wasn’t bad, now was it? But hang on, you ask. Where is the actual logic for the login and fetching the task? For right now, I’m just worried about wiring the screen itself. Yes, this unit-test covers very little ground, but we have created some level of trust that this particularl linkage in the code does work. I can now turn my back on the UI and test the actual SecurityService and TaskRepository.

One last thing missing from this article. We unwired our controller from concrete implementation of SecurityService and TaskRepository for the sake of unit-test. So now we need to inject the dependency through the constructor of the controller. Fortunately, this can be easily solved by integrating Monorail with Castle Windsor. We need to register both controllers and backing servicees to the Windsor container.

windsor.AddFacility(“rails”, new RailsFacility());

 

windsor.AddComponent<HomeController>();

windsor.AddComponent<TaskController>();

windsor.AddComponent<ISecurityService, SecurityService>();

windsor.AddComponent<ITaskRepository, TaskRepository>();

The first line is to register the facility to allow Monorail to resolve its controllers from Windsor container. The rest are to register each of the controllers and services. It uses auto-wiring to automatically introspect all necessary services to instantiate a controller. Now everytime Monorail instantiate the controller, we will get all necessary logic in place. The resulted application is pretty much the same as the original webform application. But with improved separation of concern under the hood.

An incisive reader will note that we didn’t write any unit tests for the View.  The philosophy in general is to make the hard to test view code so simple as to be reliably verified by inspection alone.  I.e., you should make the View code so simple that it’s almost impossible to screw up.

Anonymous Method is Not Closure

C# 2.0 has *tried* to embrace part of functional programming concept, the closure, and was implemented as anonymous method, which then evolved into Lambda Expression in C# 3.0. But why aren’t they closure? Does C# have true closure? Most people know the answer: NO. But few understand why. Despite its similar concept, there are some subtle differences between closure and anonymous method.

Stateful vs Stateless

The main difference between closure and anonymous method is that closure is stateful. A code is worth a thousand words:

string name = “World”;

 

HelloDelegate hello = delegate {

Console.WriteLine(“Hello, “ + name); };

 

name = “Sheep”;

hello();

A simple hello-world application, using a C# 2.0 anonymous method. What would the output be? Unlike other hello-world applications, this code will actually print “Hello, Sheep”!

But on closure, the same pseudocode will output “Hello, World”! A quick explanation is that a true closure preserves the lexical state when it is created. It indicates that the method is “closed” from its lexical environments, hence “closure”.

Whereas in C# anonymous type, the value of name when the delegate was created is NOT preserved, and the last value of name (“Sheep”) is used instead.

Instance State

This is another way to look at stateful characteristic of closure compared to anonymous method.

string name = “World”;

 

HelloDelegate hello = delegate {

       name += “!”;

       Console.WriteLine(“Hello, “ + name); };

 

HelloDelegate hello2 = delegate

{

       name += “!”;

       Console.WriteLine(“Hello2, “ + name);

};

 

hello();

hello();

hello();

hello2();

hello2();

hello2();

Console.WriteLine(“Finally: “ + name);

In C#, it will print this output:

Hello, World!

Hello, World!!

Hello, World!!!

Hello2, World!!!!

Hello2, World!!!!!

Hello2, World!!!!!!

Finally, World!!!!!!

But in Ruby’s closure, the result is:

Hello, World!

Hello, World!!

Hello, World!!!

Hello2, World!

Hello2, World!!

Hello2, World!!!

Finally, World

Note that in Ruby, each closure instance remembers its own ‘local-state’. A change on name variable on hello will affect the name variable on neither hello2 nor the environment.

Currying

You can curry a closure, but you can’t with normal C# anonymous method. No, we are not talking about some kind of tasty Thai food. Straight to the example:

ConcatDelegate concat =

delegate (string a, string b)

{

       Console.WriteLine(a + b);

};

In Ruby, one can dynamically *customise* the closure by hardwiring the first parameter as “Hello” for example. Thus calling helloConcat(“world”) will print out “Hello, world”. There is no native support on C# 2.0 to let you derive method definitions in this fashion. Wesdyer wrote on his blog how we can achieve this using Lambda Expression in C# 3.0.

In C# 2.0, LinFu provides support for this closure feature on .Net delegate. LinFu is a fairly large general-purpose AOP-centric framework by itself, and closure is only a very small part of it. This is how you can achieve currying with LinFu:

ConcatDelegate concat =

delegate (string a, string b)

{

       Console.WriteLine(a + b);

};

 

Closure hello = new Closure(

concat, “Hello, “, Args.Lambda);

 

hello.Invoke(“world”);

In the code above, we derive a new method and set the first parameter as “Hello”. Args.Lambda tells the closure to replace with actual value passed to the Invoke method when called. More on LinFu closure can be checked out here.

I will post specific blogs about LinFu in due course. I’m pretty much a new fansboy of LinFu. LinFu rocks!

Should Domain Entity Be Managed By IoC?

One question that has always been puzzling people when starting doing Domain Driven Design is how a domain entity can talk to repositories or services controlled by IoC. Particularly if those entities are (and usually they are) loaded from ORM like nHibernate. There are a lot of controversy in DDD of whether a domain entity should depend on repositories or services at first place. First, a logic that requires dependency to repositories or services indicates that it is cross-aggregate. And the basic principle is, a logic that crosses aggregate boundary should NOT live in domain entity. It should live in services, and no domain entity should be aware of it. However, in reality, most except the simplest domain logics require external services. For example, a Sales entity is responsible of calculating the payable price. And in order to do so, it needs to figure out the discount, which then involves a business-rule-engine. Hence dependency from Sales domain to BRE service. So I think the question should not be about whether an entity should depend on services. It is the fact that we have to accept that more often than not, domain entity will absolutely need services. Without it, you will most likely end up with Anemic Domain Model, which at extreme level can be very very bad based on my experience. Now back to the question: how the domain should get hold of the services, particularly if the creation is not within our control (e.g., from ORM)? Apparently this has been a regular topic in Alt.Net and DomainDrivenDesign discussions that is always brought up every 1 week or two. Some suggestions given to me by quite few people, like Alasdair Gilmour, Larry Chu, et al, have given me a new insight that I have never expected before. IoC is not only about Services. It’s also about domain entity. Out of various approaches that Larry pointed out, there are generally 2 viable solutions to solve the dependency of domain-entity without tying it up with infrastructure detail. The first approach is to leverage interceptor. If you use nHibernate, Billy McCafferty shows how we can inject DI container from nHibernate loader interceptor. My response to it, I don’t like the idea of injecting DI container to the entity. But the similar approach can be used to inject the dependencies (instead of the container) into the entity. Unity container has an elegant solution for this kind of scenario using BuildUp method. You simply have to register your *domain entity as one of IoC services*. Hence the title of this post. There is currently no similar functionality in Spring.Net or Castle Windsor. But it’s pretty straightforward to do it ourself. What we need is a custom Dependency attribute, and decorate entity’s properties with it to mark as injectable dependency:

public class Sale
{
private ICustomerRepository customerRepository;

[Dependency]
public ICustomerRepository CustomerRepository
{
set {this.customerRepository = value;}
}
}

And write the NHibernate interceptor to introspect entity’s properties that are marked with the attribute, and resolve it from IoC container:

public class DepdencyInterceptor : IInterceptor
{
public bool OnLoad(object entity, object id,

object[] state, string[] propertyNames, IType[] types)
{

// Use “setter injection” to give objects’s dependency
// for each property marked with Dependency attribute

foreach (PropertyInfo prop in entity.GetType().GetProperties())
{
if (prop.CanWrite &&
prop.GetCustomAttributes(typeof (DependencyAttribute), true) != null)
{
object dependency = IoC.Resolve(prop.DeclaringType);

prop.SetValue(entity, dependency, null);
}
}

// Even though we gave the object it’s dependency, return
// the fact that we didn’t modify the persistent properties
return false;
}

// … All other methods of IInterceptor
}

Last, register the interceptor into NHibernate session manager:

NHibernateSessionManager.Instance.RegisterInterceptor(new NHibernateDepdendencyInterceptor());

The main drawback of using nHibernate interceptor, is that it’s limited to inject dependency to entity that is publicly accessible by its aggregate root. But I personally am not too concerned about that. I will think twice if I need to push dependency to inaccessible entity of an aggregate at first place. Because, IMO, the dependency of entity in the aggregate is the dependency of the aggregate root as a whole, at least from TDD point of view. It will be difficult to test-drive the aggregate root otherwise, and if that is the case, IoC-ORM integration will be the last thing I am worried about. The second approach, particularly if you don’t use nHibernate, is by using bytecode instrumentation. For instance, using post-compilation AOP, like PostSharp, to mangle the entity’s constructor to resolve its depdendencies (decorated fields/properties) from the IoC. This is by far the most powerful solution that can solve all possible cases. It is also ORM agnostic. This approach applies with most kinds of ORM, Sql-mapper, or even without ORM. The drawback of this approach, or rather the drawback of code-mangling AOP in general, is that it involves too much dark magic that makes things less clear to follow, and can be very difficult to debug. For this reason, dynamic proxy AOP is generally favorable over code-mangling. Dynamic proxy, unfortunately for our purpose, is not an appropriate option. Many IoC containers, mostly in Java, support the second approach out of the box. But I am not aware of any similar functionality in Windsor, or most .Net IoC framework in general. So we will need to get our hand a little bit dirty with PostSharp.

Spec#, A Safe Ride in Fast Ruby World

Let’s support Mike and friends at their Spec# project with Greg Young’s “I Want Spec#” campaign. Microsoft needs to know we want it.

Finally, we are just one step away from writing a self-verifying software. This goes completely the opposite direction from Ruby. And it is truly remarkable the irony of Spec# enthusiasm among Agilists, in the middle of the hype of Ruby and dynamic CLR, again, among Agilists. I don’t know if fanatics of fast sport-car has ever wanted car manufacturers to only produce safe 80 Mph cars.

People want the freedom to write expressive code without limited by those annoying compile-time verifications. But having software that verifies itself is also dream of every developer. It must feel like a tough dilema.

I don’t know about the feeling myself. First of all, I am not a fans of Ruby and other duck-typed languages. I don’t really want to admit it, because many people say (and reempasized by Jeremy Miller) that Ruby is like a developer magnifier that allows good developers to be faster and bad developers to fail faster. So by hating Ruby, I am apparently fall in the later category. But with all my bitter experience with an uncompiled duck-typed language, I just can’t help myself from prejudice hatred toward Ruby.

But seriously I haven’t got what is so cute about Ruby. What it gives you is just little bit more than syntatic shortcut. And with the emergence of Lambda expression in C# 3.0, the only thing Ruby really gives you now is frequent runtime exceptions. We lose all the immediate feedback and verifiability of static languages. It’s also refactoring nightmare, and we all know fear of refactoring is the most common cause of poor code quality. And are syntatic shortcut and quicker coding really worth introducing few bugs and sacrificing performance?

Probably in a fast-track arena, I will prefer a formula car to a safe city car. And I might only use Ruby for fast prototype or very small project. But most other time, I like car that is cheaper to maintain, efficient, and most importantly: safe.

I think, what we really get from Ruby is the community. The vibrant attitude of the community has produced many of greatest ideas and influences in software development. And many of the ideas have come illuminating the .Net land. Castle frameworks, the best friend of all Agilist, was born from Ruby’s RoR and ActiveRecords. And Ruby’s convention over configuration has also brought a major shift in how frameworks are now written in .Net.

But apart from the community, technologically speaking… I WANT SPEC#!

TDD Screencast – Episode 1

This is the beginning of series of screencasts about applying TDD in ‘real-world’-ish .Net application. This series is my answer to recent discussion in .net-Indonesia list about using Spring and Rhino-Mock to test-drive .net applications.

Throughout the series, we will be building an example application using common Agile frameworks:
– NUnit
– Rhino-Mock
– Castle Monorail to front the web MVC
– Castle Windsor for the IoC, as opposed to Spring
– Castle Active Records backed by nHibernate.
– SqlLite to cover in-memory database-testing topic

I will also try exploring about using Linq for nHibernate, although I haven’t really tried it in real project.
For the first episode, I decided not to start with the application. This episode covers nothing but the most basic ground of Test-Driven-Development from naivitae point of view. Those with fair awareness of TDD might not get anything useful out of this. But this will set the base principle we will follow for the rest of the series.
It also (hopefully) gives me opportunity to get feedbacks and suggestions from you guys for the next episodes.

You can download the screencast at http://mihd.net/s0ad6i. (invalid)
The screencast is available at http://mihd.net/o6sx13w

You will need Techsmith codec that can be downloaded for free at http://www.techsmith.com/download/codecs.asp.

I Moved to WordPress!

I struggled a lot with Blogspot’s blog edittor. While it was clean and neat (and more importantly, allows AdSense), I finally realised it is not designed for software developers. “Who would care about tabulation in a blog?” they thought. They completely forget about us, the curly-braces geeks.

I tried out WordPress one day, and I was fascinated by how it works so well with Visual Studio’s formatting. And of course, no problem with tabulation. OK, what’s the deal with tabulation? In blogspot, because of tabulation, I needed to use HTML editor to write the whole post, and write each tab as few nbsp! I felt like I was writing a blog about .Net technology in pre-FOTRAN era.

So enough of the advertising. Let’s get this blog rolling!