2013-02-28 113 views
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. 
    } 
} 

我有几种类型的不完全,所以我希望做一个具体实施beheaviour匹配,主要为Create方法。

喜欢的东西:

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

有没有一种方法,如果一个人使用Repository<SpecificEntity>返回的SpecificEntityRepository方法的值,例如在Repository<>构造函数返回SpecificEntityRepository当参数类型等于SpecificEntity

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

回答

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 
} 

我基于存储库实例的分辨率基于对Dictionary实体类型,因为这是维护更方便,但如果我们是在谈论只是一对夫妇的具体资料库您可以改为使用if/else if

+0

谢谢你添加字典的想法。对于库的数量,我将需要它更实际。 – 2013-02-28 11:32:30

1

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

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

,以确保它是用来,你应该保护的实际构造。