c# - 如何使用 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;
}
...
}
任何建议,将不胜感激。
解决方案
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.
推荐阅读
- c - Const Struct 与 Struct 与 Const 成员
- python - 单击按钮后无法显示标签在python中使用PyQt5
- python - 结束程序后发生的奇怪的键盘中断错误
- python - 我对 json 变量设置有疑问
- javascript - Node.js(Typescript)中的 child_process.spawnSync 在 Windows 上不起作用
- javascript - 某些东西正在向我的 html 添加跨度,我不确定是什么
- git - 重置并从主分支签出到功能分支后,git 文件仍处于修改状态
- memory-leaks - 释放设备上的 cl::Buffer 和内存泄漏
- command-line - 如何在 Windows 终端中缩短 Java -jar 命令
- java - swing.JFrame 立即关闭