我正在使用MEF(依赖注入,构造函数注入)导入一个Lazy<MyForm>
对象,基本上有问题,当我显示并关闭表单并且之后尝试再次打开表单时,它将不再工作,导致对象已经处理完毕。每次我打开它时,我都想要一个全新的表单实例。懒惰<T> - 总是创建一个新的对象?
有没有类似Lazy<T>
的类,但总是给我一个新的对象?
编辑:
我不能给你我的代码的那一刻,但我会有点细讲:
哪里有两种形式:
Form1的是起点表单,其中有一个ImportingConstructor目前正在导入一个Lazy<Form2>
对象。 我的Form2
也有一个ImportingConstructor,它可以导入其他几个类。 当我点击Form1
上的按钮时,正在访问m_lazyForm2.Value
,并且Form2
显示出来。
MEF(和我的Form1)使用我自己构建的引导程序初始化。
internal class Bootstrapper<T> where T : Form
{
[Import]
private T m_frmStartup;
private CompositionContainer m_container;
public void Init()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog("."));
var batch = new CompositionBatch();
batch.AddPart(catalog);
m_container = new CompositionContainer(catalog);
m_container.ComposeParts(this);
}
public void Start()
{
Application.Run(m_frmStartup);
}
}
为什么你不能通过一个'Func'来每次都创造一个新的'T'? –
我的T班有一个ImportingConstructor以及 – Jannik
显示代码,您如何设置您的DI以及您如何使用它。 –