Thursday, July 03, 2008

Dependency injection and composition with extension methods

Muddling through the C# 3.0 updates, a colleague and I (inheritance junkies we are) came upon an interesting observation. We departed from the normal base class MyClass:

public class MyCLass
{
public void Update()
{
MyProperty="new value";
DoSomething(this);
}
}


Then we extended the class collection with an extension method (this nice code is shamelessly stolen from the Umbrella library):



public static ICollection ForEach<T>(this ICollection items, Action<T> action)
{
if (items != null)
{
foreach (T item in items)
{
action(item);
}
}
return items;
}


Intended inheritance-driven usage of this method was something like this:


var list = new List<MyCLass>();
list.ForEach(a => a.Update());


Technically there were not much sense in implementing an extension method to use it this way. So we proceeded forward and took the Update method content out of the class and injected it through the extension method:

list.ForEach
(
a =>
a.MyProperty="new value";
DoSomething(a);
)



Now we do not really need instance Update method anymore and can defer the implementation until we will be really using it.


Of course, the above implementation has significant limitations, especially if it concerns private or protected members. Also this code is not exactly DRY-friendly. From another point of view, the dependency injection pattern contradicts the concept of the "black box" to some point.


I wouldn't repeat that "LINQ is cool" but adopting this approach could bring some interesting results, what do you think?

No comments:


© 2008-2013 Michael Goldobin. All rights reserved