且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有依赖项注入的.NET 5 Windows窗体-如何将窗体属性从一个窗体传递到另一个窗体?

更新时间:2023-12-06 11:41:58

将ServiceProvider用作服务定位器在某种程度上是一种反模式.例如,***将所需的依赖项直接注入到CustomerDetail中.

The using of the ServiceProvider as a service locator is somewhat an anti-pattern. For example it's better to directly inject the needed dependencies into CustomerDetail.

public CustomerDetail(int custid, IConfiguration configuration, SomeDbNameEntities dbContext)
{
    this.Configuration = configuration;

    this.DbContext = dbContext;

    this.BillToID = custid;
    InitializeComponent();
}

关于如何传递监护权.常见的方法是使用工厂.可能看起来像这样

As how to pass in custid. A common approach is the use of factories. It could look something like this

public class CustomerDetailFactory
{
    private IServiceProvider serviceProvider;
    
    public CustomerDetailFactory(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }
    
    public CustomerDetail Create(int custid)
    {
        var configuration = (IConfiguration)this.serviceProvider.GetService(typeof(IConfiguration));
        var dbContext = (SomeDbNameEntities)this.serviceProvider.GetService(typeof(SomeDbNameEntities));
        
        return new CustomerDetail(custid, configuration, dbContext);
    }
}

然后您在CustomerSummary中使用它

Then you use it in CustomerSummary

public partial class CustomerSummary : Form
{
    private CustomerDetailFactory customerDetailFactory;
    
    public CustomerSummary(CustomerDetailFactory customerDetailFactory)
    {
        this.customerDetailFactory = customerDetailFactory;

        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;

            Form chForm = this.customerDetailFactory.Create(CustomerId);

            chForm.Show();
        }
    }   
}

别忘了在 Program.cs

Services.AddTransient<CustomerDetailFactory>();