【发布时间】:2016-02-26 06:29:17
【问题描述】:
我是 Castle Windsor 的新手(实际上是 DI),并试图使用 Windsor 解决一个场景,但我有点卡住了。给出一个想法,有 2 个不同的远程资源,我需要在第一次尝试时从其中获取给定客户的一些订单信息,这有点耗时。订单信息将来永远不会改变,因此我想将该数据存储在我的本地数据库中以供任何后续使用,这将提高我的应用程序的性能。
装饰器模式似乎是一个很好的候选者,下面是我最初的尝试。
public interface IOrderRepository
{
IEnumerable<OrderInfo> Get(string customerNo);
void Save(string customerNo, IEnumerable<OrderInfo> orders);
}
public class RealTimeRepo1 : IOrderRepository
{
public IEnumerable<OrderInfo> Get(string customerNo)
{
/// Fetch the data from remote source 1
}
public void Save(string customerNo, IEnumerable<OrderInfo> orders)
{
/// You cannot update the order info in remote source
throw new NotImplementedException();
}
}
public class RealTimeRepo2 : IOrderRepository
{
public IEnumerable<OrderInfo> Get(string customerNo)
{
/// Fetch the data from remote source 2
}
public void Save(string customerNo, IEnumerable<OrderInfo> orders)
{
/// You cannot update the order info in remote source
throw new NotImplementedException();
}
}
public LocalOrderRepo : IOrderRepository
{
public IEnumerable<OrderInfo> Get(string customerNo)
{
/// Fetch the data from local data source
}
public void Save(string customerNo, IEnumerable<OrderInfo> orders)
{
/// Save the data on local data source
}
}
public CacheOrderRepo : IOrderRepository
{
private readonly IEnumerable<IOrderRepository> realTimeRepos;
private readonly IOrderRepository localRepo;
public CacheOrderRepo(IEnumerable<IOrderRepository> realTime, IOrderRepository localRepo)
{
this.realTimeRepos = realTime;
this.localRepo = localRepo;
}
public IEnumerable<OrderInfo> Get(string customerNo)
{
List<OrderInfo> orders = this.localRepo.Get(customerNo);
if(orders == null) && (!orders.Any()
{
foreach(var r in this.realTimeRepos)
{
List<OrderInfo> t = r.Get(customerNo);
if(t.Any())
{
orders.AddRange(t);
}
}
if(orders.Any())
{
this.localRepo.save(customerNo, orders);
}
}
return orders;
}
public void Save(string customerNo, IEnumerable<OrderInfo> orders)
{
/// Save the data on local data source
}
}
我希望上面的代码 sn-p 能给出一个想法。我的难题是如何使用 Windsor 进行注册。
//regsiter
this._container.Kernal.Resolver.AddSubResolver(new
CollectionResolver(this._container.Kenrnal));
this._container.Register(
Component.For<IOrderRepository>.ImplementedBy<RealTimeRepo1>().LifeStyle.Transient,
Component.For<IOrderRepository>.ImplementedBy<RealTimeRepo2>().LifeStyle.Transient
);
使用集合子解析器,我能够注册一个可枚举的 RealTime repos 1 和 2。我应该如何注册本地 repo(即我的构造函数参数 2)?
感谢您的帮助。根据我对装饰图案或温莎城堡的理解,我也愿意提供建议......
【问题讨论】:
标签: c# castle-windsor decorator castle