每当解决组件时,是否可以创建一个新的作用域?
我正在尝试将autofac添加到旧版WinForms应用程序中,以管理依赖项并使其更具可测试性.
I am trying to add autofac to a legacy WinForms App to manage dependencies and make it more testable.
我想知道是否可以在每次注入Func时创建一个新的LifeTimeScope?
I was wondering whether it is possible to create a new LifeTimeScope every time a Func is injected?
我目前有:
public static TForm ResolveFormWithScope<TForm>(this ILifetimeScope self)
where TForm : Form
{
ILifetimeScope formScope = self.BeginLifetimeScope("FormScope");
var form = formScope.Resolve<TForm>();
form.Closed += (s, e) => formScope.Dispose();
return form;
}
但理想情况下,要避免在我的窗体中使用容器,而应使用委托工厂.
But ideally would like to avoid using the container in my Forms and instead use a delegate factory.
您正在寻找Owned<T>
隐式关系:
http://docs.autofac.org/en/latest/advanced/owned -instances.html
You are looking for the Owned<T>
implicit relationship:
http://docs.autofac.org/en/latest/advanced/owned-instances.html
注入Owned<T>
时,正如您所显示的那样,它是在其自己的生命周期范围内创建的.
When you inject an Owned<T>
it is created in its own lifetime scope just as you have shown.
如果您需要在它们自己的生命周期范围内生成多个TForm,则还可以构成隐式关系类型并注入Func<Owned<TForm>>
,每次需要TForm时都将调用该Func<Owned<TForm>>
.
If you need to generate multiple TForms in their own lifetime scopes, you can also compose the implicit relationship types and inject a Func<Owned<TForm>>
which you invoke each time you need a TForm.