开发者

MEF - How do I create a new ViewModel (or reset its state) if I'm using MEF? Also, how do I avoid memory issues?

Basically, I'm worried about a couple of things:

[Export]
public class FooViewModel : NotificationObject
{
    [Import]
    public IService1 Service1 { get; set; }

    [Import]
    public IService2 Service2 { get; set; }

    [Import]
    public BarViewModel MyBar { get; set; }

    etc.

    //This is already initialized
    public ObservableCollection<NotificationObject> CollectionOfViewModels { get; set; }

    public void SetupViewModels1()
    {
        CollectionOfViewModels.Clear();
        CollectionOfViewModels.Add(MyBar);
        CollectionOfViewModels.Add(MyOtherBar);
        CollectionOfViewModels.Add(My3rdViewModel);
        etc.
    }

    public void SetupViewModels2()
    {
        CollectionOfViewModels.Clear();
        CollectionOfViewModels.Add(MyBar);
        CollectionOfViewModels.Add(My4thViewModel);
        etc.
    }
}

[Export]
public class BarViewModel : NotificationObject
{
    [Import]
    public IService1 Service1 { get; set; }

    [Import]
    public IService2 Service2 { get; set; }

    //This is initialized and then the user starts adding values to it.
    public ObservableCollection<Object> SomeObjects { get; set; }

    public void DoSomething() { ... }
}

(1) Issue #1, I load my FooViewModel and everything is nice and dandy. I choose to load my first set of ViewModels to do some work with them. Then when I go to load my second set of ViewModels BarViewModel is still the same instance (so all of it's properties are the same, including the SomeObjects property. How do you tell it to reinitialize itself so all of it's data is cleared? If, instead I do MyBar = new MyBar() then MyBar doesn't initialize IService1 or IService2 (because MEF didn't initialize it, I did).

(2) Issue #2, When I'm not using my other ViewModels they still reside in memory because I imported them with MEF, which means their states are all there as well, which means large large collections are sitting eating away at my memory. How do you fully get rid of a ViewModel when you aren't using it anymore?

See, before I was using MEF I would do the following:

CollectionOfViewModels.Clear();
CollectionOfViewModels.Add(new MyBar());
etc.

This would mean when I do my next set of ViewModels as soon as I did CollectionOfViewModels.Clear(); any of the ViewModels that were in the collection are no longer being referenced and th开发者_StackOverflowe GC collects them. As it stands right now, doing this doesn't actually get rid of any of the ViewModels.


Are you familiar with MEF's ExportFactory functionality? It allows you to create a new instance of an export, as well as release it when you are done with it. That sounds like what you want to do here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜