1

我有一个类库来保存我的对象,所以:

xxxCommon\Objects\Customer.cs

    public class Customer
    {
        public string url { get; set; }
        public List<Telephone> telephones { get; set; }
    }

xxxData\DC\CustomerDC.cs(数据组件)

  • 此类调用许多 procs 并返回 xxxCommon\Objects 中的对象

我现在的主要问题是循环引用,要进行“延迟”加载,我需要将电话的 get 属性设置为 xxxData\DC 中的函数,如何避免这种情况?

4

3 回答 3

3

您可以使用回调方法解决循环引用。

例如,ActiveRecordSQL<T> 类具有创建实体的默认方法,但允许将其覆盖。

private Func<T> GetNewEntity;

protected ActiveRecordSQL() // constructor
{
    GetNewEntity = DefaultGetNewEntity;
}

protected Result<T> GetWithCustomEntity(SqlCommand cmd, Func<T> GetCustomEntity)
{
    GetNewEntity = GetCustomEntity;
    return Get(cmd);
}

private T DefaultGetNewEntity()
{
    return new T();
}

protected T Populate(DataRow row, T existing)
{
    T entity = existing ?? GetNewEntity();
    entity.Populate(row);
    return entity;
}

需要传递自定义函数的类可以使用 lambda 表达式,或者使用正确的签名传递对其自身函数的引用。

        ReferrerInfo = dc.Referrers.GetCustomReferrer(referrerID, () => new ReferrerFacade()).Data as ReferrerFacade;

"GetCustomReferrer" calls intermediate methods that simply pass the method to "GetWithCustomEntity". "ReferrerFacade" subclasses an entity and lives in a different project. Passing the callback method allows calls "backward" across the existing reference.

于 2011-05-02T20:33:45.627 回答
2

解决循环依赖的一种方法是在两个程序集之间放置一个层:

而不是这种情况;

装配模型:

public class Customer{ 
    //...
}

装配数据:

public class CustomerDAO{
    public Customer LoadCustomer(int id){
         return new Customer(id,...);
    }
}

其中模型程序集引用数据程序集并且数据无法返回模型以实例化客户。

你可以改为;

装配模型:

public class CustomerModel:Customer{}
public class ModelFactoryImp:ModelFactory{
    public Customer CreateCustomer(int id,//...customer params){
        return new CustomerModel(...);
    }
}

装配模型接口:

public abstract class Customer{//...}
public abstract ModelFactory{
    Customer CreateCustomer(int id,//...customer params);
}

装配数据:

public class CustomerDAO{
    private ModelFactory _modelFactory;

    public CustomerDAO(ModelFactory modelFactory){
         _modelFactory = modelFactory;
    }

    public Customer LoadCustomer(int id)
    { 
        // Data Access Code
        return _modelFactory.CreateCustomer(id,//...cutomer params);
    }
}

模型和数据程序集都依赖于 ModelInterfaces 层,并且您将 ModelFactory 类的实现传递给客户数据访问对象,以便它可以创建客户。

于 2011-05-02T20:28:50.043 回答
0

这看起来像是WeakReferences的合适用法- 您不想随时将整个客户/电话列表保存在缓存中,对吗?API 文档实际上以管理大型缓存为例。

于 2011-05-02T20:08:22.143 回答