2017-05-22 12 views
2

私のプロジェクトでは、SQLDependencyとDependency Injectionを使いたいと思います。私は以下のようなDBContextでIAreaRepositoryを通過した場合ので、ここに私のコードはDIを使用したSQLDependency

public interface IAreaRepository 
{ 
    string GetAreaQuery(); 
    List<Area> GetAreas(); 
} 

public class AreaRepository: IAreaRepository 
{ 
    public AreaRepository(DbContext dbContext) 
    { 
     _dbContext = dbContext; 
    } 

    public string GetAreaQuery() 
    { 
     return _dbContext.Areas.ToString(); 
    } 

    public string GetAreas() 
    { 
     return _dbContext.Areas.ToList(); 
    } 
} 

。ここでは、私のクラスは

ある
public class AreaDataProvider 
{ 
    private readonly AreaRepository _areaRepository; 
    public AreaDataProvider(IAreaRepository areaRepository) 
    { 
     _areaRepository = areaRepository; 
    } 

    public void RegisterForNotification() 
    { 
     var connectionString = WebConfigurationManager.AppSettings["ConnectionString"]; 
     using (var connection = new SqlConnection(connectionString)) 
     { 
      var areaQuery = _areaRepository.GetAreaQuery(); // Line 1 
      connection.Open(); 
      using (var oCommand = new SqlCommand(areaQuery, connection)) 
     { 
      // Starting the listener infrastructure... 
      SqlDependency.Start(connectionString); 

      var oDependency = new SqlDependency(oCommand); 
      oDependency.OnChange += OnNotificationChange; 

      var reader = oCommand.ExecuteReader(); 
     } 
    } 

    private void OnNotificationChange(object sender, SqlNotificationEventArgs e) 
    { 
     // Area Table has changed, Get the latest state from Db 
     var areas = _areaRepository.GetAreas(); // Line 2 
     RegisterForNotification(); 
    } 
} 

ある今、私の問題は、AreaDataProviderを初期化呼び出す方法です。

using (AppContext context = new AppContext()) 
{ 
    AreaDataProvider provider = new AreaDataProvider(new AreaRepository(context)); 
    provider.RegisterForNotification(); 
} 

私DbContextはAreaDataProviderクラス全体で単一DbContextを達成するための最良の方法は何行目1および2に異なるものになります。

+0

行1と2は何ですか?とにかく、独自のDbContextインスタンスを作成してリポジトリに渡す 'AreaDataProvider'オブジェクトのデフォルトのコンストラクタを持つことができます。 – PoweredByOrange

+0

1行目と2行目は上記のコードでコメントされていますが、基本的にはリポジトリ(Db)にアクセスする2つの独立した呼び出しです。 – Pankaj

答えて

1

DbContextは、1行目に異なることになり、2

ありません、それはしません。コンストラクタに渡されるのと同じAreaRepositoryになります。

関連する問題