每当解决组件时,是否可以创建一个新的作用域? [英] Is it possible to create a new scope whenever a component is resolved?

查看:75
本文介绍了每当解决组件时,是否可以创建一个新的作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将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.

这篇关于每当解决组件时,是否可以创建一个新的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆