我可以在工厂内创建一个隐式的Lifetime范围吗? [英] Can I create an implicit Lifetime scope within a factory?

查看:97
本文介绍了我可以在工厂内创建一个隐式的Lifetime范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Autofac是否支持使用工厂的隐式生存期范围?例如,我希望能够执行以下操作

Does Autofac support implicit lifetime scopes for the use of a factory? For example, I would like to be able to do the following

public class Session : IDisposable
{
    public Session(A a, B b, C c)
    {
        ...
    }
} 

...

using (var session = _sessionFactory())
{
    ...
}

然后在每次调用_sessionFactory时,Autofac会自动创建一个嵌套的生存期作用域吗?

and then upon each call to the _sessionFactory have Autofac automatically create a nested lifetime scope?

推荐答案

是.让工厂返回Owned<Session>. 拥有的实例表示调用代码负责处理该服务.实际上,如果您从容器中解析Func<Owned<Session>>,则Autofac会为您提供一个自动工厂来生成此类实例.

Yes. Let the factory return Owned<Session>. Owned instances indicates that the calling code is responsible for disposing the service. Actually, if you resolve a Func<Owned<Session>> from the container, Autofac will give you an automatic factory that produces such instances.

这篇关于我可以在工厂内创建一个隐式的Lifetime范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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