首页 > 解决方案 > 如何使用 Autofac 和 Winforms 来注入依赖项

问题描述

我正在尝试学习 Autofac。我找不到适用于 Winforms 的工作示例。在我的program.cs我有这个:

public static IContainer Container { get; private set; }

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
     var builder = new ContainerBuilder();
     builder.Register(c => new MyContext());
     Container = builder.Build();
     ...
     using (var loginForm = new LoginForm(new MyContext()))
     {
         DialogResult results;
         do
         {
             results = loginForm.ShowDialog();
             if (results == DialogResult.Cancel)
                 Environment.Exit(1);
         } while (results != DialogResult.OK);
            
         UserName = loginForm.ValidatedUserName;
     }
}

MyContext()是一个 DbContext。我想注入MyContext()我的LoginForm(),但我还没有完全弄清楚。的前几行LoginForm()

public partial class LoginForm : Form
{
    private readonly MyContext _context;

    public LoginForm(MyContext context)
    {
        InitializeComponent();
        _context = context;
    }
    ...
}

任何建议,将不胜感激。

标签: c#winformsautofac

解决方案


Register the form too:

var builder = new ContainerBuilder();
builder.RegisterType<MyContext>();
builder.RegisterType<LoginForm>();
Container = builder.Build();

And then resolve the form from the container:

using (var loginForm = Container.Resolve<LoginForm>())
{
    DialogResult results;
    do
    {
        results = loginForm.ShowDialog();
        if (results == DialogResult.Cancel)
            Environment.Exit(1);
    } while (results != DialogResult.OK);
       
    UserName = loginForm.ValidatedUserName;
}

Then MyContext will automatically be injected when the form is resolved. By default Autofac registrations are registered as "self" (i.e. they can be resolved as their own type) and "instance per dependency" (you get a new one each time you resolve it), so you are safe to keep the using in this case.


推荐阅读