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

은 내가 특정 구현을 할 수 있도록 정확하게 주로 Create 방법를 들어, beheaviour 일치하지 않는 여러 종류가 있습니다. 같은

뭔가 :

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

는 사람이 Repository<SpecificEntity>를 사용하는 경우 인수의 형태가 SpecificEntity 같을 때 Repository<>의 생성자에서 SpecificEntityRepository을 반환 예를 들어, SpecificEntityRepository의 방법의 값을 반환하는 방법이 있나요?

이 작업을 수행하는 일반적인 방법을 찾고 있습니다. 내 프로젝트의 최종 버전에는 최대 200 개의 특정 리포지토리가있을 수 있으며이 중 95 %는 일반적인 기능입니다.

답변

1

사람이 Repository<SpecificEntity>을 만들지 못하도록하려면 Repository 생성자를 protected으로 만들고 인스턴스 생성을 공장 메서드를 통해서만 허용 할 수 있습니다. 예를 들어

: 그 유지하는 것이 더 편리하지만 우리가 '경우 특정 저장소의 단지 몇 가지에 대해 이야기 다시 때문에 Dictionary에 엔티티 유형에 따라 저장소 인스턴스의 해상도를 기반

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 
} 

형식 대신 if/ else if을 사용할 수 있습니다.

+0

사전 아이디어를 제공해 주셔서 감사합니다. 저장소의 수가 많으면 많은 연습이 필요합니다. –

1

특정 생성자를 호출 한 후에는 개체의 클래스를 변경할 수 없습니다.
는 그러나 대신 직접 실제 생성자를 호출하는 팩토리 메소드를 사용할 수 있습니다

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

가 사용되었는지 확인하려면 보호 된 실제 생성자를해야한다.