这是一个使用代理模式实现延迟加载的示例。
Person类将与您的其他模型一起存在。Children被标记为虚拟,因此它可以在PersonProxy类中被覆盖。
public class Person {
public int Id;
public virtual IList<Child> Children { get; set; }
}
PersonRepository类将与其余存储库一起使用。 我在这个类中包括了获取子项的方法,但如果您愿意,也可以将其放在ChildRepository类中。
public class PersonRepository {
public Person FindById(int id) {
Person person = new PersonProxy();
return person;
}
public IList<Child> GetChildrenForPerson(int personId) {
}
}
PersonProxy类与您的存储库一起使用。它继承自Person并执行延迟加载。您还可以使用布尔值来检查是否已经加载,而不是检查Children == null。
public class PersonProxy : Person {
private PersonRepository _personRepository = new PersonRepository();
public override IList<Child> Children {
get {
if (base.Children == null)
base.Children = _personRepository.GetChildrenForPerson(this.Id);
return base.Children;
}
set { base.Children = value; }
}
}
你可以这样使用它。
Person person = new PersonRepository().FindById(1)
Console.WriteLine(person.Children.Count)
当然,如果您不想直接调用PersonRepository,您可以让PersonProxy接受一个指向PersonRepository的接口,并通过服务访问它。