Skip to content

Instantly share code, notes, and snippets.

@ArildF
Created June 27, 2011 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArildF/1049747 to your computer and use it in GitHub Desktop.
Save ArildF/1049747 to your computer and use it in GitHub Desktop.
Open generic decorators vs closed generic services
using System;
using System.Linq;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Machine.Specifications;
namespace RequestHandlers.Tests
{
public interface IThing<T>
{
void Foo();
}
public class ThingImplementation : IThing<string>
{
public static bool Called;
public void Foo()
{
Called = true;
}
}
public class ThingDecorator<T>: IThing<T>
{
private readonly IThing<T> _inner;
public static bool Called;
public ThingDecorator(IThing<T> inner)
{
_inner = inner;
}
public void Foo()
{
Called = true;
_inner.Foo();
}
}
[Subject("Creating decorators")]
public class when_wrapping_a_service_in_a_decorator
{
private Establish context = () =>
{
var container = new WindsorContainer();
container.Kernel.AddHandlerSelector(new HandlerSelector());
container.Register(Component.For(typeof(IThing<>)).ImplementedBy(typeof(ThingDecorator<>)).Parameters(Parameter.ForKey("inner").Eq("${Implementation}")));
container.Register(Component.For(typeof (IThing<string>)).ImplementedBy(typeof (ThingImplementation)).Named("Implementation"));
_thing = container.Resolve<IThing<string>>();
};
private Because of = () => _thing.Foo();
private It should_be_the_decorator_type = () => _thing.ShouldBeOfType<ThingDecorator<string>>();
private It should_call_the_inner_service = () => ThingImplementation.Called.ShouldBeTrue();
private It should_call_the_decorator = () => ThingDecorator<string>.Called.ShouldBeTrue();
private static IThing<string> _thing;
}
public class HandlerSelector : IHandlerSelector
{
public bool HasOpinionAbout(string key, Type service)
{
return service.Name.Contains("Thing");
}
public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
{
return handlers.FirstOrDefault(h => h.ComponentModel.Implementation.Name.Contains("Decorator"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment