Reputation: 2744
I want to use SQLDependency along with Dependency Injection in my project. Here is my code
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();
}
}
and Here is my class
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();
}
}
Now My issue is how to call initialise AreaDataProvider, because if I passed IAreaRepository with a DBContext like the one below.
using (AppContext context = new AppContext())
{
AreaDataProvider provider = new AreaDataProvider(new AreaRepository(context));
provider.RegisterForNotification();
}
My DbContext will be different in Line 1 and 2. What is the best way to achieve single DbContext across the AreaDataProvider class.
Upvotes: 2
Views: 333
Reputation: 89036
DbContext will be different in Line 1 and 2.
No it won't. It will be the same AreaRepository passed to the constructor.
Upvotes: 1