我正在使用 MVVM light 及其 Ioc 来做一个 wpf 应用程序SimpleIoc
.
我实现了这样的存储库模式:
public interface ICrud<T> where T : class
{
IEnumerable<T> GetAll();
Task<IEnumerable<T>> AsyncGetAll();
void AddNew(params T[] items);
void Delete(params T[] items);
void Update(params T[] items);
void SaveOrUpdate(params T[] items);
}
public class Crud<T> : ICrud<T> where T : class
{
public void AddNew(params T[] items)
{
using (var context = new DataEntities())
{
foreach (T item in items)
{
context.Entry(item).State = System.Data.Entity.EntityState.Added;
}
context.SaveChanges();
}
}
public void Delete(params T[] items)
{
using (var context = new DataEntities())
{
foreach (T item in items)
{
context.Entry(item).State = System.Data.Entity.EntityState.Deleted;
}
context.SaveChanges();
}
}
public void Update(params T[] items)
{
using (var context = new DataEntities())
{
foreach (T item in items)
{
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
context.SaveChanges ();
}
}
public void SaveOrUpdate(params T[] items)
{
using (var context = new DataEntities())
{
foreach (T item in items)
{
try
{
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
catch (Exception)
{
context.Entry(item).State = System.Data.Entity.EntityState.Added;
context.SaveChanges();
}
}
}
}
public IEnumerable<T> GetAll()
{
using (var context = new DataEntities())
{
DbSet<T> dbSet = context.Set<T>();
return dbSet.AsEnumerable().ToList();
}
}
public Task<IEnumerable<T>> AsyncGetAll()
{
return Task.Factory.StartNew(() =>
{
var context = new DataEntities();
DbSet<T> dbSet = context.Set<T>();
return dbSet.AsEnumerable();
});
}
}
在视图模型定位器中,我像这样注入依赖项:
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<IDataService, DataService>();
SimpleIoc.Default.Register<ICrud<student>, Crud<student>>();
SimpleIoc.Default.Register<ICrud<prof>, Crud<prof>>();
//Add the other EF entities dependencies
}
我的问题是,当我要执行 CRUD 操作时,我必须在调用之前实例化 EF 实体,例如:
SimpleIoc.Default.GetInstance<ICrud<student>>().AddNew();
我需要知道 :
- 像上面那样实例化一个EF,是否违反了这个概念依赖注入
- 如果是这样,我该如何解决这个问题?
你不应该注入实体。实体不是服务。您使用依赖项注入构建的对象图应该仅包含服务。任何包含运行时数据(实体、消息、DTO)的内容都应该使用方法调用通过构建的对象图传递。
看看例如this and this回答和this博客文章。
在单个类中混合数据和行为会使测试 DI 配置变得更加困难,并且难以应用横切关注点。但除此之外,将运行时数据(例如实体)注入到服务的构造函数中会导致歧义,因为不清楚将哪个实体注入到构造函数中。以一些ICustomerService
这取决于Customer
实体在其构造函数中。我们应该在这里注入哪个实体,因为我们可能有数千个。尽管这可以通过在我们创建的位置实施选择标准来解决ICustomerService
实现(我们的组合根),这使得 DI 配置非常复杂,使得验证配置变得非常困难,并导致应用程序中不应包含任何业务逻辑的部分产生业务逻辑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)