【发布时间】:2016-04-26 05:57:11
【问题描述】:
目前,我的代码与此类似(只是为了说明一点而缩短):
DAL
存储库接口
public interface IRepository<TEntity, in TKey>
{
IList<TEntity> GetAll();
TEntity Get(TKey id);
TEntity Add(TEntity item);
TEntity Update(TEntity item);
bool Remove(TKey id);
}
基础 EF 存储库
public class BaseEFRepository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity: class, IEntity<TKey> where TKey: struct
{
protected readonly DbContext _dbContext;
public BaseRepository()
{
_dbContext = new MyDB();
_dbContext.Configuration.ProxyCreationEnabled = false;
_dbContext.Configuration.LazyLoadingEnabled = false;
}
public virtual TEntity Get(TKey id)
{
return _dbContext.Set<TEntity>().Find(id);
}
public virtual IList<TEntity> GetAll()
{
return _dbContext.Set<TEntity>()
.ToList();
}
public virtual TEntity Add(TEntity item)
{
_dbContext.Set<TEntity>().Add(item);
_dbContext.SaveChanges();
return item;
}
.....
.....
}
基础存储库的示例实现
public interface IContactsRepository : IRepository<Contact, long>
{
Contact GetByEmployeeId(string empId, ContactType type);
IList<Contact> GetByEmployeeId(string empId);
}
public class ContactsRepository : BaseEFRepository<Contact, long>, IContactsRepository
{
public Contact GetByEmployeeId(string empId, ContactType type)
{
var contact = _dbContext.Set<Contact>()
.FirstOrDefault(d => d.EmployeeId == empId && d.ContactType == type);
return contact;
}
public IList<Contact> GetByEmployeeId(string empId)
{
var contacts = _dbContext.Set<Contact>()
.Where(d => d.EmployeeId == empId)
.ToList();
return contacts;
}
}
BLL
public class Contacts
{
public Contact Get(long id)
{
IContactsRepository repo = ResolveRepository<IContactsRepository>();
var contact = repo.Get(id);
return contact;
}
public Contact GetByEmployeeId(string empId, ContactType type)
{
IContactsRepository repo = ResolveRepository<IContactsRepository>();
return repo.GetByEmployeeId(empId, type);
}
.......
.......
}
现在,一切都很好。我可以简单地做这样的事情:
var _contacts = new Contacts();
var contact = _contacts.GetByEmployeeId("C1112", ContactType.Emergency);
当我阅读this blog post 时开始感到困惑,作者说使用如下代码:
IContactsRepository repo = ResolveRepository<IContactsRepository>();
是一种糟糕的技术,它是反模式的,应该将所有内容都注入代码的根部。我看不出如何使用存储库模式来做到这一点。我正在使用 WCF 使用它。那么,我到底如何从 WCF 的第一次调用中注入所有内容?我无法得到它。我在这里错过了什么?
最后一件事,在这种情况下,WCF 是最后一层,它应该只知道它之前的层,即 BLL 层。如果我要按照该博客的作者的建议实现任何东西,我会让 WCF 层意识到 DAL 层,这不是不好的做法吗?如果我错了,请纠正我。
【问题讨论】:
-
那么,您的应用程序是 WCF 应用程序吗?它是托管在 IIS 中还是自托管?在控制台应用程序中?还是在 Windows 服务中?
标签: c# design-patterns dependency-injection inversion-of-control repository-pattern