我有一门课,我想装饰两次。但是,当我解决这个类时,Windsor 只装饰它一次,而不是使用我的 2 个装饰器。我不确定为什么会这样,因为我在我要解决的课程之前注册了两个装饰器,这就是我理解装饰器与 Windsor 一起工作的方式。
这是我的代码。
public interface IQueryExecuter
{
TReturn Execute<TReturn>(IQuery<TReturn> query);
}
public class QueryLoggingDecorator : IQueryExecuter
{
private ILogger _logger = NullLogger.Instance;
public ILogger Logger
{
set { _logger = value; }
}
public TReturn Execute<TReturn>(IQuery<TReturn> query)
{
_logger.Info("Before query execute");
var queryResults = query.Execute();
_logger.Info("After query execute");
return queryResults;
}
}
public class QueryTransactionDecorator : IQueryExecuter
{
public TReturn Execute<TReturn>(IQuery<TReturn> query)
{
try
{
Console.WriteLine("Beginning transaction");
var queryResults = query.Execute();
Console.WriteLine("Comitting transaction");
return queryResults;
}
catch (Exception)
{
Console.WriteLine("Rolling back transaction");
throw;
}
}
}
public interface IQuery<out TReturn>
{
TReturn Execute();
}
public class Query : IQuery<string>
{
public string Execute()
{
Console.WriteLine("Executing query");
var queryResults = Path.GetRandomFileName();
return queryResults;
}
}
这是我的温莎注册码。
public class DefaultInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component
.For<IQueryExecuter>()
.ImplementedBy<QueryLoggingDecorator>()
.LifestyleTransient());
container.Register(Component
.For<IQueryExecuter>()
.ImplementedBy<QueryTransactionDecorator>()
.LifestyleTransient());
container.Register(Component
.For<IQueryExecuter>()
.ImplementedBy<QueryExecuter>()
.LifestyleTransient());
}
}
最后,这是我的调用代码。
var container = new WindsorContainer();
container.Install(FromAssembly.This());
var queryExecuter = container.Resolve<IQueryExecuter>();
var queryResults = queryExecuter.Execute(new Query());
我错过了什么?
我希望当我解决IQueryExecuter
温莎会用QueryLoggingDecorator
然后装饰QueryTransactionDecorator
。