【问题标题】:Repository Pattern and Model Relationships and Dependency Injection存储库模式和模型关系以及依赖注入
【发布时间】:2015-01-12 21:18:45
【问题描述】:

我对存储库模式的使用非常陌生,并且我正在努力在使用存储库时如何在我的模型中实现关系。例如,我有以下两个存储库接口: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 对象中的getter 延迟加载来请求实际地址是否可以?另外,如果IPersonRepository 具有GetPersons() 之类的方法,我会将IPersonRepository 注入到Address 对象中吗?我问这个是因为我正在重构一些代码以使用存储库模式,并希望利用依赖注入来准备它以便在以后更好地测试。

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

【问题讨论】:

  • 在对象本身中引用存储库似乎非常奇怪。这样做的原因是什么?
  • 好吧,我想我只是不知道如何做得更好。 :) 在支持从数据存储延迟加载的同时,您将如何建立与Address 的关系?
  • 您正在尝试做 EF 已经为您做的事情。 EF 生成代理类以注入额外的代码以在延迟加载的情况下使用。查看 this 文章,看看它是否对您有帮助。

标签: c# sharepoint dependency-injection repository-pattern


【解决方案1】:

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

相反,在 Address 模型中,我将有一个 personId 字段,或者如果您在每个地址跟踪多个人,则使用 personId 的集合。

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

【讨论】:

  • 如果我弄错了,请纠正我,但是使用名为 GetByPersonId(int personId) 的方法会有什么不同吗?我仍然需要对 Person 对象 Address getter 中的 AddressRepository 进行某种引用才能接收实际地址。
  • 不一定要在人号里面。你可以把它放在那个人身上,但是将存储库注入到你的实体中并不是很干净。我自己,无论在哪里需要,我都会获取一个人,然后当我需要地址时,使用该人的 ID 直接调用存储库上的方法。例如,如果您在 MVC 控制器中执行此操作,我会将两个存储库都注入到控制器中,并在必要时进行调用。
  • 好的,我知道了,但是当我使用存储库手动请求地址时,我可以省略 Address 属性,并且不会有 Persons 地址的延迟加载支持。导航属性还有其他方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
相关资源
最近更新 更多