使用 Autofac 时多次触发事件
Events are fired more than once when using Autofac
我有像这样使用 Autofac 注册的表格
builder.RegisterAssemblyTypes(assembly)
.AssignableTo<Form>()
.As<IMyForm, MyForm>()
.AsImplementedInterfaces();
一切正常,但是当我将 Load 事件添加到 MyForm 时,发生了一些不好的事情。如果我第一次打开 MyForm 会触发加载事件,但如果我多次打开它,加载事件也会多次触发。为了防止这种情况,我添加了看起来像
的 OnClosing 方法
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Load -= MyForm_Load;
}
有更好的方法吗?
我会在 MyForm_Load
本身取消注册该事件,这样您就更加一致了。另外我不认为你的代码是错误的。
我有像这样使用 Autofac 注册的表格
builder.RegisterAssemblyTypes(assembly)
.AssignableTo<Form>()
.As<IMyForm, MyForm>()
.AsImplementedInterfaces();
一切正常,但是当我将 Load 事件添加到 MyForm 时,发生了一些不好的事情。如果我第一次打开 MyForm 会触发加载事件,但如果我多次打开它,加载事件也会多次触发。为了防止这种情况,我添加了看起来像
的 OnClosing 方法protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Load -= MyForm_Load;
}
有更好的方法吗?
我会在 MyForm_Load
本身取消注册该事件,这样您就更加一致了。另外我不认为你的代码是错误的。