目前,我的代码与此类似(为了说明一点而缩短):
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);
当我阅读时,困惑开始了这篇博文 http://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container,作者说使用如下代码:
IContactsRepository repo = ResolveRepository<IContactsRepository>();
是一种糟糕的技术,它是反模式的,应该将所有内容注入代码的根部。我不知道如何使用存储库模式来做到这一点。我正在使用 WCF 来使用它。那么,我到底如何从 WCF 中的第一次调用中注入所有内容呢?我听不懂。我在这里缺少什么?
最后一件事,在这种情况下,WCF 是最后一层,它应该只知道它之前的层,即 BLL 层。如果我要按照该博客作者的建议实现任何内容,我将使 WCF 层了解 DAL 层,这不是不好的做法吗?如果我错了请纠正我。