我正在编写系统托盘实用程序,您可以从菜单中为应用程序打开几种不同的表单.我正在使用autofac来解决这些表单的创建,必要时给出我的主要表单Func和Func依赖项.
如果用户选择激活表单的选项,如果已经显示它应该获得焦点,否则autofac应该创建一个新表单.
我真的不希望这些表单在没有使用的情况下存放在内存中,所以当用户关闭它时,我目前正在让表单自行处理.
我需要知道的是我如何通知autofac表格已被处理,以便:
我一直在阅读Autofac wiki,我猜我只需要正确设置LifetimeScope.
你所做的有点超出规范,所以我认为 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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后就可以注册了
builder
.Register(c => new SingletonFormProvider<YourForm>(() => new YourForm())
.AsSelf()
.SingleInstance();
builder
.Register(c => c.Resolve<SingletonFormProvider<YourForm>>().CurrentInstance)
.AsSelf();
Run Code Online (Sandbox Code Playgroud)