1

私はEntityFramework5.0でリポジトリパターンを実装しています-少なくとも私はそうだと思います:)。これは私が使用しているものです

public abstract class GenericRepository<C, T> :
 IGenericRepository<T>
    where T : class
    where C : DbContext, new()
{
    private bool disposed = false;
    private C _entities = new C();
    protected C Context
    {
        get { return _entities; }
        set { _entities = value; }
    }

    public virtual IQueryable<T> GetAll()
    {
        IQueryable<T> query = _entities.Set<T>();
        return query;
    }

    public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> query = _entities.Set<T>().Where(predicate);
        return query;
    }

    public virtual void Add(T entity)
    {
        _entities.Set<T>().Add(entity);
    }

    public virtual void Delete(T entity)
    {
        _entities.Set<T>().Remove(entity);
    }

    public virtual void Edit(T entity)
    {
        _entities.Entry(entity).State = System.Data.EntityState.Modified;
    }

    public virtual bool Save()
    {
        return (_entities.SaveChanges() > 0);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
            if (disposing)
                _entities.Dispose();

        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

その後、このクラスは特定のリポジトリクラスに継承されます-たとえばPlaceRepository

public class PlaceRepository : GenericRepository<DbEntities, Place>, IPlaceRepository
{ }

別のレイヤー(ビジネスレイヤー)では、PlaceRepositoryクラスのインスタンスを作成しています-PlaceControllerというクラスで。このクラスには、PlaceEntity(CRUD)用の特定のメソッドがあります。このPlaceControllerには、データベースにPlaceエンティティを挿入するために使用されるメソッドが1つありますが、同時に別のテーブル(たとえばCountryテーブル)に何かを挿入しています。Countryテーブルに対するCRUD操作の場合、CountryRepositoryという別のリポジトリがあります。

要約すると、Place Controllerの私のメソッドは、2つの異なるリポジトリのインスタンスを作成し、それらのメソッドを使用して、DbContextの2つの異なるコンテキストを作成します。以下のコードを参照してください

public class PlaceController 
{ 
   public bool InsertPlace(Place toInsert)
   {
      PlaceRepository _placeRepo = new PlaceRepository();
      _placeRepo.Add(toInsert);

      Country _country = new Country();

      _country.Name = "default";

      CountryRepository _countryRepo = new CountryRepository();

      _countryRepo.Add(_country);

     //now i must call save on bothRepositories
     _countryRepo.Save(); _placeRepo.Save();

}
}

このシナリオについて意見が必要です。2つの挿入を行うためにコンテキストクラスの2つのインスタンスを作成するのは良いですか?そうでない場合は、別のパターンの使用/実装を検討する必要がありますか?

4

1 に答える 1

1

そのためにはIoC(DI)コンテナを使用する必要があります。これは、プロジェクト全体でコンテキストの1つのインスタンスを使用するのに役立ちます。serviceLocatorパターンの方法も調べることができますが、IoC(DI)コンテナーを使用することをお勧めします。Castle.Windsor(DIパターンの実現)が好きで、Ninjectも見ることができます。

于 2013-02-14T14:54:52.380 に答える