我對存儲庫模式的使用相當陌生,而且我正在努力如何在使用存儲庫的模型中實現關係。因此,例如我有以下兩種庫接口:IPersonRepository
和IAddressRepository
存儲庫模式和模型關係和依賴注入
public interface IPersonRepository
{
IList<Person> GetAll();
Person GetById(int id);
}
public interface IAddressRepository
{
IList<Address> GetAll();
Address GetById(int id);
Address GetByPerson(Person person);
}
和兩個模型類:Person
和Address
public class Person
{
private IAddressRepository _addressRepository;
public string FirstName { get; set; }
public string LastName { get; set; }
private Address _address;
public Address Address
{
get { return _addressRepository.GetByPerson(this); }
set { _address = value; }
}
Person(string firstName, string lastName, IAddressRepository addressRepository)
{
this.FirstName = firstName;
this.LastName = lastName;
this._addressRepository = addressRepository;
}
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public List<Person> Persons { get; set; }
Address(string street, string city, string zip)
{
this.Street = street;
this.City = city;
this.Zip = zip;
}
}
所以現在我的問題是:是否有罰款注入的IAddressRepository
成Person
類並通過從實際的Person
對象中的獲取器中延遲加載請求實際地址?另外,如果它有一個像GetPersons()
這樣的方法,我會注入IPersonRepository
到Address
對象嗎?我這樣問是因爲我重構了一些代碼來使用存儲庫模式,並希望利用依賴注入來使它在稍後的時間點更好地測試。
此外:我沒有使用任何ORM,因爲我正在SharePoint環境中開發,我正在使用SharePoint列表作爲域模型的實際數據存儲。
在對象本身中引用存儲庫似乎非常奇怪。做這件事的原因是什麼? –
嗯,我想我只是不知道如何做得更好。 :)在支持數據存儲的延遲加載的同時,如何建立與「Address」的關係? –
你正試圖做EF已經爲你做的事情。 EF生成代理類以注入額外的代碼以用於延遲加載。 檢查** [this](http://www.alachisoft.com/resources/articles/entity-framework-poco-lazy-loading.html)**文章,看看它是否有幫助。 – Nilesh