2015-10-02 43 views
1

我正在使用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); 
    } 
} 
+2

为什么你不能通过一个'Func '来每次都创造一个新的'T'? –

+0

我的T班有一个ImportingConstructor以及 – Jannik

+1

显示代码,您如何设置您的DI以及您如何使用它。 –

回答

0

好的,正如我在评论中已经说过的,我自己找到了解决方案。

的解决方案是:

  1. 更改我的Lazy<T>进口ExportFactory<T>进口
  2. 导出我所有的意见与[PartCreationPolicy(CreationPolicy.NonShared)]属性

这样,你叫m_myViewExportFactory.CreateExport().Value每次,它会给你是你的观点的新例子。

1

你可能会寻找一个factory method,无论是传递给您的形式,直接委托,或包裹成一个潜在的匿名实现一些接口。

A Lazy<T>确实只是在最后的可能时间点,即确实需要时初始化一些T。为此,它可以简单地调用T类型的默认构造函数,或者以Func<T>代表的形式执行提供的工厂方法。

您可以将Func<T>传递给您的表单而不是Lazy<T>包装。