Caliburn Micro EventAggregator订阅/取消订阅同一ViewModel

时间:2015-06-12 08:49:01

标签: c# ioc-container caliburn.micro eventaggregator

我最近发现我的Handle()方法在单次发布后被多次调用...并且发现已停用和关闭的ViewModel实例实际上没有处理掉并且一直接收消息!我正在寻找一种方法来正确处理过时的视图模型或者只是从EventAggregator订阅中删除它们。

我的shell是

Conductor<T>.Collection.OneActive, IScreenEx where T : class, IScreenEx

已执行的项目在SimpleContainer中注册如下:

container.PerRequest<ILinkageMovements, LinkageGraphViewModel>();

并像这样激活:

    public X SwitchToNamed<X>(String key) where X : T
    {
        var existing = Items.FirstOrDefault(y => y.GetType() == typeof(X) && y.UniqueKey == key);

        if (existing == null)
            existing = Items.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(typeof(X)) && x.UniqueKey == key);

        if (existing != null)
        {
            ChangeActiveItem(existing, false);
            return (X)existing;
        }
        else
        {
            X vm = container.GetInstance<X>();
            vm.UniqueKey = key;
            ActivateItem(vm);
            return vm;
        }
    }

ViewModel以这种方式构建:

    public LinkageGraphViewModel
        (
            Caliburn.Micro.SimpleContainer container,
            Caliburn.Micro.IEventAggregator eventAggregator,
            IDialogManager dialogs,
            IDataService dataService,
            IReferentialData refData
        )
        : base(container, eventAggregator, dialogs, dataService, refData)
    {
        DisplayName = Strings.Movements;
    }

最后,基类构造函数是:

    public BaseConductor(SimpleContainer container, IEventAggregator eventAggregator, IDialogManager dialogs)
    {
        this.container = container;
        this.eventAggregator = eventAggregator;
        this.eventAggregator.Subscribe(this);
        this.Dialogs = dialogs;
    }

请帮忙。

1 个答案:

答案 0 :(得分:1)

Unsubscribe界面上有IEventAggregator方法。

关于什么时候打电话给它的问题的答案取决于你的体系结构 - 你发布的代码不再解释你的视图模型何时不再需要 - 它们可能永远留在项目中。

通常,您在OnActivate订阅并在OnDeactivate取消订阅但是您的代码在构造函数中订阅,因此我猜您可能希望订阅非活动模型,因此CanClose可能是另一位候选人。

相关问题