问题
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