1

我有一个通用的存储库类。

public class Repository<TEntity> where TEntity : class
{
    public virtual TEntity Create()
    {
        // Create implementation.
    }
    public virtual bool Add(TEntity entity)
    {
        // Add implementation.
    }
    public virtual bool Delete(TEntity entity)
    {
        // Delete implementation.
    }
    public virtual int SaveChanges()
    {
        // Save changes implementation.
    }
}

我有几种与行为不完全匹配的类型,主要是针对Create方法,所以我想做一个具体的实现。

就像是:

public class SpecificEntityRepository : Repository<SpecificEntity>
{
    public override SpecificEntity Create()
    {
        // Other create implementation.
    }
}

有没有一种方法可以让一个人Repository<SpecificEntity>用来返回 的方法的值SpecificEntityRepository,例如在参数类型等于时在SpecificEntityRepository构造函数中返回?Repository<>SpecificEntity

我正在寻找一种通用的方法来做到这一点。在我的项目的最终版本中可能有多达 200 个特定的存储库,其中 95% 的功能是通用的。

4

2 回答 2

1

如果您想阻止人们创建一个Repository<SpecificEntity>,您可以创建Repository构造函数protected并只允许通过工厂方法创建实例。

例如:

public class Repository<TEntity> where TEntity : class
{
    private static readonly Dictionary<Type, Func<object>> specificRepositories =
        new Dictionary<Type, Func<object>>
        {
            { typeof(SpecificEntity), () => new SpecificRepository() }
        };

    protected Repository() {}

    public static Repository<T> Create<T>() where T : class
    {
        var entityType = typeof(T);
        if (specificRepositories.ContainsKey(entityType)) {
            return (Repository<T>)specificRepositories[entityType]();
        }
        else {
            return new Repository<T>();
        }
    }

    // default implementations omitted
}

我将基于实体类型的存储库实例的解析基于 a,Dictionary因为这样更便于维护,但如果我们只讨论几个特定的​​存储库类型,您可以使用if/else if代替。

于 2013-02-28T11:25:38.953 回答
1

一旦调用了特定的构造函数,就无法更改对象的类。
但是您可以使用工厂方法而不是直接调用实际的构造函数:

public static Repository<T> CreateRepository<T>() {
    if (typeof(T) == typeof(SpecificEntity)) {
        return new SpecificEntityRepository();
    }
    return new Repository<T>();
}

为了确保它被使用,你应该保护实际的构造函数。

于 2013-02-28T11:25:45.623 回答