dur*_*ess 5 .net c# architecture entity-framework structure
我正在使用POCO开发原型EF应用程序.主要是作为框架的介绍我想知道在一个漂亮的结构中设置应用程序的好方法.后来我打算将WCF纳入其中.
我所做的是以下内容:
1)我创建了一个edmx文件,但是Code Generation Property设置为None并生成了我的数据库模式,
2)我创建的POCO看起来像:
public class Person
{
public Person()
{
}
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
3)我创建了一个Context
public class PocoContext : ObjectContext, IPocoContext
{
private IObjectSet<Person> persons;
public PocoContext() : base("name=PocoContainer", "PocoContainer")
{
ContextOptions.LazyLoadingEnabled = true;
persons= CreateObjectSet<Person>();
}
public IObjectSet<Person> Persons
{
get
{
return persons;
}
}
public int Save()
{
return base.SaveChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
界面如下所示:
public interface IPocoContext
{
IObjectSet<Person> Persons { get; }
int Save();
}
Run Code Online (Sandbox Code Playgroud)
4)最后我创建了一个存储库,实现了一个接口:
public class PersonRepository : IEntityRepository<Person>
{
private IPocoContext context;
public PersonRepository()
{
context = new PocoContext();
}
public PersonRepository(IPocoContext context)
{
this.context = context;
}
// other methods from IEntityRepository<T>
}
public interface IEntityRepository<T>
{
void Add(T entity);
List<T> GetAll();
T GetById(int id);
void Delete(T entity);
}
Run Code Online (Sandbox Code Playgroud)
现在,当我继续玩这个时,这个设计要求我每次想要获取或改变一些数据时实例化一个存储库,如下所示:
using (var context = new PocoContext())
{
PersonRepository prep = new PersonRepository();
List<Person> pers = prep.GetAll();
}
Run Code Online (Sandbox Code Playgroud)
不知何故,这只是感觉错误和缺陷,另一方面,只是实例化派生上下文中的每个存储库也感觉不太好,因为可能实例化我可能根本不需要的对象.
关于如何使这个设计听起来的任何提示?我应该这样离开吗?这样做时我应该添加或避免的任何事情?
我不明白这部分:
using (var context = new PocoContext())
{
PersonRepository prep = new PersonRepository();
List<Person> pers = prep.GetAll();
}
Run Code Online (Sandbox Code Playgroud)
如果调用存储库构造函数而不将上下文作为参数传递,为什么要在外部范围中创建上下文?使用多个上下文只会让事情变得更加困难。另外,如果您的外部块仅创建该类的实例,那么为存储库创建接口并尝试隐藏它有什么意义呢?
你的做法正确吗?一般来说是的。您应该使用单个上下文进行逻辑操作(工作单元),如果您的存储库通过构造函数获取上下文,您需要为每个上下文创建一组新的存储库。这通常是通过依赖注入来实现的。
只是在派生上下文中实例化每个存储库感觉也不太好,因为可能会实例化我可能根本不需要的对象。
好吧,这可以通过延迟初始化很容易地解决:
private SomeRepositoryType _someRepository
public SomeRepositoryType SomeRepository
{
get { _someRepository ?? (_someRepository = new SomeRepositoryType(context)) }
}
Run Code Online (Sandbox Code Playgroud)
但我不会将其放在上下文中。我可能会在某些数据访问工厂中使用它,因为它应该在上下文之外,并且使用多个存储库将单个工厂作为注入传递到类/方法更简单。
顺便提一句。使用存储库您会获得什么价值?
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |