C# 存储库模式和模型关系以及依赖项注入

C# 存储库模式和模型关系以及依赖项注入,c#,sharepoint,dependency-injection,repository-pattern,C#,Sharepoint,Dependency Injection,Repository Pattern,我对使用存储库模式非常陌生,我正在努力在使用存储库的同时实现模型中的关系。例如,我有以下两个存储库接口:IPersonRepository和iadressrepository public interface IPersonRepository { IList<Person> GetAll(); Person GetById(int id); } public interface IAddressRepository { IList<Address&g

我对使用存储库模式非常陌生,我正在努力在使用存储库的同时实现模型中的关系。例如,我有以下两个存储库接口:
IPersonRepository
iadressrepository

public interface IPersonRepository
{
    IList<Person> GetAll();
    Person GetById(int id);
}

public interface IAddressRepository
{
    IList<Address> GetAll();
    Address GetById(int id);
    Address GetByPerson(Person person);
}
所以现在我的问题是:将
IAddressRepository
注入
Person
类中,并通过从实际
Person
对象中的getter延迟加载来请求实际地址,这样可以吗?另外,如果
GetPersons()
这样的方法,我是否会将
IPersonRepository
注入
地址
对象?我这样问是因为我正在重构一些代码以使用存储库模式,并希望利用依赖项注入来准备它,以便在以后更好地进行测试


此外:在SharePoint环境中开发时,我没有使用任何ORM,我使用SharePoint列表作为域模型的实际数据存储。

如果我自己这样做,我不会将存储库注入到您的模型中

相反,在地址模型上,我会有一个personId字段,或者如果每个地址跟踪不止一个人,则是personId的集合


这样做,您可以在地址存储库中有一个名为
GetByPersonId(int personId)
的方法,该方法将通过检查此人的id是否与地址上的id匹配或包含传入的personId的地址上的id集合匹配来获取此人的地址

在对象本身中引用存储库似乎非常奇怪。这样做的原因是什么?嗯,我想我只是不知道如何做得更好在支持从数据存储延迟加载的同时,您如何建立与
地址的关系?您正在尝试EF已经为您做的事情。EF生成代理类来注入额外的代码,以便在延迟加载的情况下使用。检查这篇文章,看看它是否对您有帮助。如果我弄错了,请纠正我,但使用名为
GetByPersonId(int personId)
的方法会有什么不同吗?我仍然需要在
Person
objects
Address
getter中对
AddressRepository
进行某种引用才能接收实际地址。它不必在Person no中。您可以在Person上使用它,但将存储库注入到您的实体中并不是很好和干净。我自己,无论在哪里需要它,我都会找到一个人,然后当我需要地址时,直接使用这个人的ID调用存储库中的方法。例如,如果您在MVC控制器中执行此操作,我会将这两个存储库都注入控制器,并在必要时进行调用。好的,我得到了这一点,但是当我使用存储库手动请求地址时,我可以省略
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;
    }
}