Winforms 如何使用autofac解析(非模态)表单的单个实例,直到该表单被释放?
我正在编写一个系统托盘实用程序,从菜单中可以为应用程序打开几个不同的表单。我正在使用autofac解决这些表单的创建问题,必要时提供我的主表单Func和Func依赖项 如果用户选择激活表单的选项,如果已经显示,则应接收焦点,否则autofac应创建新表单 我真的不希望这些表单在不使用时保存在内存中,所以我现在让表单在用户关闭时自行处理 我需要知道的是如何通知autofac该表单已被处理,以便:Winforms 如何使用autofac解析(非模态)表单的单个实例,直到该表单被释放?,winforms,autofac,Winforms,Autofac,我正在编写一个系统托盘实用程序,从菜单中可以为应用程序打开几个不同的表单。我正在使用autofac解决这些表单的创建问题,必要时提供我的主表单Func和Func依赖项 如果用户选择激活表单的选项,如果已经显示,则应接收焦点,否则autofac应创建新表单 我真的不希望这些表单在不使用时保存在内存中,所以我现在让表单在用户关闭时自行处理 我需要知道的是如何通知autofac该表单已被处理,以便: 它不再包含对已处理表单的引用(因此可以进行垃圾收集) 当我下一次请求autofac获取表单实例时,它会
我一直在阅读Autofac wiki,我猜我只需要正确设置生命周期范围。您所做的有点超出标准,因此我认为Autofac的标准生命周期范围不适用。我有一个类似的场景,我有一个类型,我想要一个可替换/可重新加载的类型的单个实例。我所做的是注册一个包装器类。适应Winform,看起来像
public class SingletonFormProvider<TForm> : IDisposable
where TForm: Form
{
private TForm _currentInstance;
private Func<TForm> _createForm;
public SingletonFormProvider(Func<TForm> createForm)
{
_createForm = createForm;
}
public TForm CurrentInstance
{
get
{
if (_currentInstance == null)
_currentInstance = _createForm();
// TODO here: wire into _currentInstance close event
// to null _currentInstance field
return _currentInstance;
}
}
public void Close()
{
if (_currentInstance == null) return;
_currentInstance.Dispose();
_currentInstance = null;
}
public void Dispose()
{
Close();
}
}
公共类SingletonFormProvider:IDisposable
其中TForm:Form
{
私有TForm\u currentInstance;
私有函数(createForm),;
公共SingletonFormProvider(Func createForm)
{
_createForm=createForm;
}
公共TForm CurrentInstance
{
得到
{
如果(_currentInstance==null)
_currentInstance=_createForm();
//此处的待办事项:连接到_currentInstanceclose事件
//设置为空\u currentInstance字段
返回_currentInstance;
}
}
公众假期结束()
{
if(_currentInstance==null)返回;
_currentInstance.Dispose();
_currentInstance=null;
}
公共空间处置()
{
Close();
}
}
然后你就可以注册了
builder
.Register(c => new SingletonFormProvider<YourForm>(() => new YourForm())
.AsSelf()
.SingleInstance();
builder
.Register(c => c.Resolve<SingletonFormProvider<YourForm>>().CurrentInstance)
.AsSelf();
builder
.Register(c=>new SingletonFormProvider(()=>new YourForm())
.AsSelf()
.SingleInstance();
建设者
.Register(c=>c.Resolve().CurrentInstance)
.AsSelf();
谢谢Jim,我扩展了您的解决方案,将表单提供程序注册为,并为我的表单依赖项使用一个接口。要创建访问这些表单接口的服务,我让它们使用autofac解析的表单提供程序。这样,我的表单就可以添加依赖项,而无需修改autofac注册代码。@RhysParry我能请您详细介绍一下扩展的解决方案吗?最好是为我和其他人发布源代码,让他们从中得到启发