你为什么不把你的解决方案分成不同的项目?
我喜欢使用代理模式。
在我的解决方案我有三个项目:
- MVC(有代理项目的引用)
- 代理(这是一个类库,持有是一个引用到WCF项目)
- WCF (该项目知道数据库,我的实体框架是在这里)
我想这个形象可能会有所帮助:
使用这种方法,您可以在代理项目中拥有不同的存储库,您可以在它们之间进行交换。当我们进行单元测试时,或者当我们需要使用缓存存储库时,这非常有用。
public abstract class Repository<T>
{
public abstract T GetById(int id);
}
使用这一个单元测试
public class CustomerRepository : Repository<CustomerEntity>
{
public override CustomerEntity GetById(int id)
{
return new CustomerEntity()
{
Id = id,
Name = "Customer " + id
};
}
}
用这个当你需要访问外部服务
public class RemoteOrderRepository : Repository<OrderEntity>
{
public override OrderEntity GetById(int id)
{
// You can access your external service here
}
}
用这个把缓存的优势
public class CachedOrderRepository : RemoteOrderRepository
{
public override OrderEntity GetById(int id)
{
string cacheKey = "Order" + id;
var entity = MemoryCache.Default[cacheKey] as OrderEntity;
if(entity == null)
{
entity = base.GetById(id);
var cacheItem = new CacheItem(cacheKey, entity);
var policy = new CacheItemPolicy();
MemoryCache.Default.Add(cacheItem, policy);
}
return entity;
}
}