Monday, November 9, 2009

Functional programming using Unity

C# 3.0 comes with functional programming capabilities that can become very handy if combined with a dependency injection framework as Unity.
Take a look at the following example. The function ‘doThis’ can be register in the unity container just like any other instance of a type. At the time of registration the function ‘doThis’ isn’t called yet. It’s not even called at the time of resolving the function ‘doThis’ from the container. This idea is very useful when doing lazy things with Unity.
//create a unity container
IUnityContainer container = new UnityContainer();   
//define a function
Func<bool> doThis = delegate 
{ 
Debugger.Break(); 
return true; 
}; 
//register the function as instance
//function will not execute during registration 
container.RegisterInstance(doThis);
//resolve the function from the container
//function will not execute during the resolving
var f = container.Resolve<Func<bool>>();
//will execute here:-) 
f();