我建议一些不同的东西......使用延迟加载类:
public class Lazy<T>
{
T value;
Func<T> loader;
public Lazy(T value) { this.value = value; }
public Lazy(Func<T> loader { this.loader = loader; }
T Value
{
get
{
if (loader != null)
{
value = loader();
loader = null;
}
return value;
}
public static implicit operator T(Lazy<T> lazy)
{
return lazy.Value;
}
public static implicit operator Lazy<T>(T value)
{
return new Lazy<T>(value);
}
}
一旦你得到它,你就不需要在你的对象中注入 dao 了:
public class Transaction
{
private static readonly Lazy<Customer> customer;
public Transaction(Lazy<Customer> customer)
{
this.customer = customer;
}
public Customer Customer
{
get { return customer; } // implicit cast happen here
}
}
创建未绑定到数据库的 Transcation 对象时:
new Transaction(new Customer(..)) // implicite cast
//from Customer to Lazy<Customer>..
从存储库中的数据库重新生成事务时:
public Transaction GetTransaction(Guid id)
{
custmerId = ... // find the customer id
return new Transaction(() => dao.GetCustomer(customerId));
}
发生了两件有趣的事情: - 您的域对象可以在有或没有数据访问的情况下使用,它变得对数据访问无知。唯一的小转折是允许传递一个提供对象而不是对象本身的函数。- Lazy 类是内部可变的,但可以用作不可变值。readonly 关键字保持其语义,因为它的内容不能从外部更改。
当您希望该字段可写时,只需删除 readonly 关键字。当分配一个新值时,由于隐式转换,将使用新值创建一个新的 Lazy。
编辑:我在这里写了博客:
http://www.thinkbeforecoding.com/post/2009/02/07/Lazy-load-and-persistence-ignorance