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 pub Kensington

Windsor Castle pub Kensington

SEPTEMBER 03, 2025

There s a great deal of character and genuine old-fashioned charm here, with a wealth of dark oak furnishings, sturdy high-backed…

Read More
Windsor Castle pictures

Windsor Castle pictures

SEPTEMBER 03, 2025

A Maundy Thursday tradition came to Windsor for the first time since 1959 today. The Queen attended the Royal Maundy Service…

Read More