Is it possible to create a new scope whenever a component is resolved?

半世苍凉 提交于 2019-12-12 02:39:11

问题


I am trying to add autofac to a legacy WinForms App to manage dependencies and make it more testable.

I was wondering whether it is possible to create a new LifeTimeScope every time a Func is injected?

I currently have:

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.


回答1:


You are looking for the Owned<T> implicit relationship: http://docs.autofac.org/en/latest/advanced/owned-instances.html

When you inject an Owned<T> it is created in its own lifetime scope just as you have shown.

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.



来源:https://stackoverflow.com/questions/39155170/is-it-possible-to-create-a-new-scope-whenever-a-component-is-resolved

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!