我的解决方案中有几个项目可以访问相同的数据,因此稍后我将在单独的项目中实现数据访问。目前我正在使用 EF4、通用存储库和工作单元模式。我已经设计了我的数据访问以支持依赖注入,并且我想使用 Ninject。这是我到目前为止的示例
public class Account
{
public int Id { get; set; }
public Guid WebId { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
}
public interface IRepository<T>
{
IEnumerable<T> Get(Expression<Func<T, bool>> filter, Func<IQueryable<T>);
T GetById(int id);
void Update(T dinner);
void Insert(T dinner);
void Delete(int id);
void Save();
}
我还有一个存储库实现,我不会在这里发布它以供篇幅。
我的 UnitOfWork 看起来像这样
public class UnitOfWork
{
private Repository<Account> _accountRepository;
public IRepository<Account> AccountRepository
{
get
{
if (this._accountRepository == null)
{
_accountRepository = new Repository<Account>();
}
return _accountRepository;
}
}
}
我如何以及在哪里设置 ninject 来自动解析我的存储库,这样我就可以使用该接口而无需在我的工作单元中实例化它。这是正确的做法还是我完全错误地理解了 DI?这是我认为我希望我的工作单元看起来像的样子
public class UnitOfWork
{
IKernel _kernel;
public UnitOfWork()
{
_kernel = new StandardKernel();
}
private IRepository<Account> _accountRepository;
public IRepository<Account> AccountRepository
{
get
{
if (this._accountRepository == null)
{
_accountRepository = _kernel.Get<IRepository<Account>>();;
}
return _accountRepository;
}
}
}