26 May 2008

Slingin' Menus

by mo

I received a question the other day on building menu’s in a win forms application. I wasn’t sure of a clean way of doing it, so I thought I would put together a sample app to see if I could come up with something. I’m not sure I’m completely happy with what I’ve got so far, but my goal was to be able to drop in new menu items, and menu groups without a lot of ceremony and configuration.

The guts of it depends on castle windsor to glue most of the pieces together using the mass component registration api. I found it really hard to test, but was please with how easy it just kind of worked!

public class WindsorContainerFactory : IWindsorContainerFactory {
  private static IWindsorContainer container;
  private IComponentExclusionSpecification criteriaToSatisfy;

  public WindsorContainerFactory() : this(new ComponentExclusionSpecification()) {}

  public WindsorContainerFactory(IComponentExclusionSpecification criteriaToSatisfy) {
    this.criteriaToSatisfy = criteriaToSatisfy;

  public IWindsorContainer Create() {
    if (null == container) {
      container = new WindsorContainer();
                delegate(ComponentRegistration registration) {
                  this.LogInformational("{1}-{0}", registration.Implementation, registration.ServiceType.Name);
                  if (registration.Implementation.GetInterfaces().Length == 0) {
    return container;

The other neat piece that kind of made things easy to get up and running was the concept of a default repository. (I picked up this bit of knowledge from Oren at DevTeach.)

public class DefaultRepository<T> : IRepository<T> {
  private IDependencyRegistry registry;

  public DefaultRepository(IDependencyRegistry registry) {
    this.registry = registry;

  public IEnumerable<T> All() {
    return registry.AllImplementationsOf<T>();

This was the only implementation of a repository in the system, and it was used for a IRepository<IMenuItem> and IRepository<ISubMenu>. I just created a new implementation of an IMenuItem. or ISubMenu` and it picked it up via Windsor’s mass component registration.

public class MainMenuPresenter : IMainMenuPresenter {
  private readonly IMainMenuView mainMenu;
  private readonly IRepository<ISubMenu> repository;
  private readonly ISubMenuItemComparer comparer;

  public MainMenuPresenter(IMainMenuView mainMenu, IRepository<ISubMenu> repository, ISubMenuItemComparer comparer) {
    this.mainMenu = mainMenu;
    this.repository = repository;
    this.comparer = comparer;

  public void Initialize() {
    foreach (var subMenuToAddToMainMenu in repository.All().SortedUsing(comparer)) {

I also spent a little time playing with Gallio. I had some issue with conflicts between the version of Castle.Microkernel that I was toying with and the one that comes with gallio. I wasn’t able to resolve the issue, but after looking into the concept behind Gallio, I like the idea. Kind of neat stuff!