New Guard step off to march up

Windsor Castle closures

I've been experimenting with using named delegates instead of single-method interfaces. This has some advantages for code size, as we can go from (some linebreaks removed so as not to overstate the case):

public interface IProductSource { IEnumerable

GetProducts; } public class DataContextProductSource : IProductSource { private readonly DataContext _DataContext; public DataContextProductSource(DataContext dataContext) { if (dataContext == null) throw new ArgumentNullException("dataContext"); _DataContext = dataContext; } public IEnumerable

GetProducts { return _DataContext.Products.AsEnumerable; } }

to:

public delegate IEnumerable

DGetProducts; public static class DataContextFunctions { public DGetProducts GetProducts(DataContext dataContext) { if (dataContext == null) throw new ArgumentNullException("dataContext"); return => dataContext.Products.AsEnumerable; } }

This is basically taking advantage of the fact that once you go far enough with dependency injection, a lot of classes become little more than closures. Those classes can be replaced with functions that return lambdas. Entire sets of related functions (that don't need to encapsulate any mutable state, but would have been expressed using classes in "standard" dependency injection), can then be rolled up into a static class (or "module" in VB parlance).

This is all well and good, but I'm having trouble finding the best way to register these static methods with Castle Windsor. Methods with no dependencies are easy:

Component.For.Instance(Integers.GetOneToTen)

But our DataContextFunctions.GetProducts from above has some dependencies. The best way I've found to register this is:

Component.For.UsingFactoryMethod( kernel => DataContextFunctions.GetProducts(kernel.Resolve)

This can get quite verbose, and obviously having to ask the kernel directly for each dependency kind of defeats the point a bit. It seems to me that all the static information that a container should need is available, so it should be possible to do this.

Source: stackoverflow.com
Video on topic: Windsor Castle closures
2016 Windsor Castle parade
2016 Windsor Castle parade
CASTLE.MOV
CASTLE.MOV

Interesting facts
Share this Post

Related posts

Windsor Castle Tours

Windsor Castle Tours

APRIL 19, 2024

Windsor Castle is the oldest and largest inhabited castle in the world, and the Queen of England’s favourite. Located on…

Read More
Windsor Castle, located

Windsor Castle, located

APRIL 19, 2024

It’s that time of year again when the Windsor Festival, strikes a pitch-perfect note. This year will see the festival celebrate…

Read More