Created
June 27, 2011 20:24
-
-
Save ArildF/1049747 to your computer and use it in GitHub Desktop.
Open generic decorators vs closed generic services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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