I am upgrading a .NET Framework Windows Form Application to .NET 5 using Dependency Injection (DI). There are forms that call other forms and pass in form properties as parameters. So, CustomerSummary
calls CustomerDetail
and passes in a CustomerId
. The following demonstrated how to call one form from another:
But, it doesn't show how MainForm
can pass a parameter to SecondForm
. How can I pass a parameter from one form to another when using DI? Or, do I just create a new
form and pass the values, along with the ServiceProvider
, in the parameter list (this seems to defeat the purpose of DI)? The code is as follows:
CustomerSummary.cs
public partial class CustomerSummary : Form
{
protected IConfiguration Configuration { get; set; }
protected SomeDbNameEntities DbContext { get; set; }
protected IServiceProvider ServiceProvider { get; set; }
public CustomerSummary(IServiceProvider objServiceProvider)
{
this.Configuration = (IConfiguration)objServiceProvider.GetService(typeof(IConfiguration));
this.DbContext = (SomeDbNameEntities)objServiceProvider.GetService(typeof(SomeDbNameEntities));
this.ServiceProvider = (IServiceProvider)objServiceProvider.GetService(typeof(IServiceProvider));
InitializeComponent();
BindCustomerGrid();
}
private void dgvCustomer_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if ((dgvCustomer.SelectedRows[0].Cells[0].Value) != DBNull.Value)
{
int CustomerId = (int)dgvCustomer.SelectedRows[0].Cells[0].Value;
// .NET Framework
CustomerDetail chForm = new CustomerDetail(CustomerId);
// .NET 5. How do I pass the CustomerId?
Form chForm = (CustomerDetail)ServiceProvider.GetService(typeof(CustomerDetail));
chForm.Show();
}
}
}
CustomerDetail.cs
public partial class CustomerDetail : Form
{
protected IConfiguration Configuration { get; set; }
protected SomeDbNameEntities DbContext { get; set; }
protected IServiceProvider ServiceProvider { get; set; }
int BillToID;
public CustomerDetail(int custid, IServiceProvider objServiceProvider)
{
this.Configuration = (IConfiguration)objServiceProvider.GetService(typeof(IConfiguration));
this.DbContext = (SomeDbNameEntities)objServiceProvider.GetService(typeof(SomeDbNameEntities));
this.ServiceProvider = (IServiceProvider)objServiceProvider.GetService(typeof(IServiceProvider));
this.BillToID = custid;
InitializeComponent();
}
}
UPDATE
The CustomerSummary
form itself is called from another form (called MainMenu
) with the following call:
Form chForm = (CustomerSummary)ServiceProvider.GetService(typeof(CustomerSummary));
chForm.Show()
This is why you see apparent anti-pattern behavior. Since you changed the CustomerSummary
constructor (I basically added two in order to get the MainForm
call to work), how would that change your solution because right now I get a build error relating to the fact that the wrong constructors are being called. Do I need to create a CustomerSummaryFactory
?