使用共享服务的示例

使用共享服务的示例

本文介绍了使用共享服务的示例.棱镜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 5 个模块,我使用 EventAggregator 模式在模块之间进行通信.在我看来,我的代码变得丑陋,并且在我的项目中使用 EventAggregator 是一种糟糕的设计.

I have 5 modules and I am using EventAggregator pattern to communicate between modules. And it seems to me that my code becomes ugly and it is bad design to use EventAggregator in my project.

模块间通信的三种方式:

There are three ways to communicate between modules:

  • 松散耦合的事件
  • 共享服务
  • 共享资源

我想了解更多关于共享服务的通信.我发现的是一篇关于 来自 Prism ToolKit 的 StockTrader 应用程序.

I would like to know more about communication by Shared Services. What I've found is an article about StockTrader application from Prism ToolKit.

是否有一些在 Prism 中使用 共享服务 的更轻量和更清晰的示例,其中可以看到使用 共享服务 的模块之间的对话?(可下载的代码将不胜感激)

Is there some more lightweight and clearer example of using Shared Services in Prism where it is possible to see talking between modules using Shared Services? (downloadable code would be highly appreciated)

推荐答案

您的代码在哪些方面变得丑陋?EventAggregator 是一项共享服务,如果您愿意的话.

In which way is your code getting ugly? The EventAggregator is a shared service, if you like.

您将服务接口放入共享程序集中,然后一个模块可以将数据推送到服务中,而另一个模块从服务中获取数据.

You put a service interface in a shared assembly, and then one module can, say, push data into the service while another module get's the data from the service.

共享程序集

public interface IMySharedService
{
    void AddData( object newData );
    object GetData();
    event System.Action<object> DataArrived;
}

第一个通信模块

// this class has to be resolved from the unity container, perhaps via AutoWireViewModel
internal class SomeClass
{
    public SomeClass( IMySharedService sharedService )
    {
        _sharedService = sharedService;
    }

    public void PerformImport( IEnumerable data )
    {
        foreach (var item in data)
            _sharedService.AddData( item );
    }

    private readonly IMySharedService _sharedService;
}

第二通信模块

// this class has to be resolved from the same unity container as SomeClass (see above)
internal class SomeOtherClass
{
    public SomeOtherClass( IMySharedService sharedService )
    {
        _sharedService = sharedService;
        _sharedService.DataArrived += OnNewData;
    }

    public void ProcessData()
    {
        var item = _sharedService.GetData();
        if (item == null)
            return;

        // Do something with the item...
    }

    private readonly IMySharedService _sharedService;
    private void OnNewData( object item )
    {
        // Do something with the item...
    }
}

一些其他模块的初始化

// this provides the instance of the shared service that will be injected in SomeClass and SomeOtherClass
_unityContainer.RegisterType<IMySharedService,MySharedServiceImplementation>( new ContainerControlledLifetimeManager() );

这篇关于使用共享服务的示例.棱镜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:22