Windsor, classroom injection container
Hi I have the following component registered with Castle Windsor:
public class CommandDispatcher : IServiceCommandDispatcher
{
private readonly IWindsorContainer container;
public CommandDispatcher(IWindsorContainer container)
{
this.container = container;
}
#region IServiceCommandDispatcher Members
public void Dispatch<TCommand>(TCommand command) where TCommand : IServiceCommand
{
var handler = container.Resolve<IServiceCommandHandler<TCommand>>();
handler.Handle(command);
}
#endregion
}
And the dispatcher is registered like this:
Component
.For<IServiceCommandDispatcher>()
.ImplementedBy<CommandDispatcher>(),
But the container field is null when I resolve the dispatcher instance. What should I do to pass the container to the allowed children?
source to share
Windsor solves this problem for you with a typed Factory tool .
In the example below, I want the implementation ICommandHandlerFactory
to resolve my command handler from my windsor container.
class CommandDispatcher : IServiceCommandDispatcher
{
private readonly ICommandHandlerFactory factory;
public CommandDispatcher(ICommandHandlerFactory factory)
{
this.factory = factory;
}
public void Dispatch<T>(T command) where T : IServiceCommand
{
var handler = this.factory.Create(command);
handler.Handle(command);
this.factory.Destroy(handler);
}
}
For this I need to create an interface ICommandHandlerFactory
.
public interface ICommandHandlerFactory
{
Handles<T> Create<T>(T command) where T : IServiceCommand;
void Destroy(object handler);
}
No implementation ICommandHandlerFactory
is required as Windsor will create an implementation. Windsor uses the convention that a method that returns an object is a method resolve
and a method that returns void is a method release
.
To register Factory you need to enable using Castle.Facilities.TypedFactory
and then register Factory like this
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ICommandHandlerFactory>()
.AsFactory()
);
To recap , you don't need to write implementation code for the factory.
source to share