2

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.

asked May 22, 2017 at 16:29
2
  • What's line 1 and 2? Anyways you could have a default constructor for the AreaDataProvider object that creates its own instance of DbContext and passes that to the repository. Commented May 22, 2017 at 16:42
  • Line 1 and 2 are commented in code above, Basically, they are two separate calls where repository (Db) is accessed. Commented May 22, 2017 at 18:14

1 Answer 1

1

DbContext will be different in Line 1 and 2.

No it won't. It will be the same AreaRepository passed to the constructor.

answered May 22, 2017 at 19:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.