我正在尝试使用城堡windsor来装饰我的命令处理程序,但似乎我的注册不正确,因为该类没有装饰。
我有以下安装程序:
internal class CommandsInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IDbConnection>()
.UsingFactoryMethod(() => ConnectionHelper.GetOpenDbConnection(Connection.DatabaseName.ReedOnline))
.LifestylePerWebRequest());
container.Register(
Classes
.FromAssemblyContaining<EcruiterCommands>()
.Where(t => t.Name.EndsWith("Commands"))
.WithService
.AllInterfaces().LifestylePerWebRequest());
container.Register(
Classes
.FromAssemblyContaining<EcruiterCommands>()
.Where(t => t.Name.EndsWith("CommandHandler"))
.WithService.AllInterfaces()
.LifestylePerWebRequest());
container.Register(Component.For(typeof (ICommandHandler<>))
.ImplementedBy(typeof (TransactionCommandHandlerDecorator<>))
.IsDefault()
.LifestylePerWebRequest());
container.Register(Component.For(typeof (ICommandHandler<>))
.ImplementedBy(typeof (ExceptionHandlingCommandHandlerDecorator<>))
.IsDefault()
.LifestylePerWebRequest());
}
}
这是我的装饰者:
namespace TempSearch.Ioc.Decorators.CommandHandlers
{
public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decorated;
public TransactionCommandHandlerDecorator(ICommandHandler<TCommand> decorated)
{
this.decorated = decorated;
}
public void Handle(TCommand command)
{
using (var scope = new TransactionScope())
{
decorated.Handle(command);
scope.Complete();
}
}
}
}
此外,我想知道我的装饰者是否应该存在于合成词根或他们正在装饰的类的程序集中。现在我已将它们移动到组合根,因为城堡windsor试图将其装饰器与其他类一起注册,我会得到错误:
Component TempSearch.Command.Data.Decorators.TransactionCommandHandlerDecorator`1 could not be registered.
There is already a component with that name.
Did you want to modify the existing component instead?
If not, make sure you specify a unique name.
答案 0 :(得分:1)
首先,关于“已注册”错误,您要两次注册组件
container.Register(
Classes
.FromAssemblyContaining<EcruiterCommands>()
.BasedOn(typeof (ICommandHandler<>))
.WithService.AllInterfaces()
.LifestylePerWebRequest());
这会注册所有基于ICommandHandler<>
的类,因此TransactionCommandHandlerDecorator
已经注册
关于你想要的装饰者模式,我将使用城堡的interceptors来实现它。我发现在城堡中装饰者的模式是not very easy;回答的问题很古老,Castle从那时起就发生了变化,所以我可能错了,但拦截器就是你想要的。