I am really new to dependency injection concept. So maybe I made it wrong, I am not sure. Let me describe the issue.
I have a Windows forms app. In main form, I have called Entity Framework db context
DBContext context = new DBContext();
I have several forms and business logic for every entity. What I am trying to do is: the user opens a form, there is a datagridview in the form to display data. Its data source is context.
User enters some data, then, if user clicks ok button, I call context.saveChanges();
If user clicks cancel button I don't call and I expect data doesn't be saved.
Here is the related code. In mainform I call my form and inject context:
dataForm form = new dataForm(context);
form.ShowDialog();
In dataForm user sees the data, crud. I inject the same context which is coming from mainform to logic class:
DBContext context;
dataLogic logic;
public dataForm(DBContext context)
{
this.context = context;
logic = new dataLogic(context);
}
private void okButton_Click(object sender, EventArgs e)
{
context.SaveChanges();
DialogResult = DialogResult.OK;
}
private void cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
The problem here is, since I use dependency injection (context in mainform -> inject to dataform -> inject to logic) and I use the context as datasource for datagridview even if I don't call context.SaveChanges();
the data has been saved to context. So user clicks cancel and still sees the modified data. Unless it restart the application.
To fix the issue I can create new instances of context in logic classes or data forms but this solution will come with problems that DI solves.
So, how should I implement my code? Did I made DI not correct?