问题
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:
- Loosely coupled events
- Shared services
- Shared resources
I would like to know more about communication by Shared Services. What I've found is an article about StockTrader application from Prism ToolKit.
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)
回答1:
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.
Edit:
Shared assembly
public interface IMySharedService
{
void AddData( object newData );
object GetData();
event System.Action<object> DataArrived;
}
First communicating module
// 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;
}
Second communicating module
// 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...
}
}
Some other module's initialization
// this provides the instance of the shared service that will be injected in SomeClass and SomeOtherClass
_unityContainer.RegisterType<IMySharedService,MySharedServiceImplementation>( new ContainerControlledLifetimeManager() );
回答2:
The Prism Library repo on GitHub has an up to date version of the Stock Trader sample application, which includes service examples and source code for you to look at, and download.
https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/StockTraderRI
来源:https://stackoverflow.com/questions/34741727/example-of-using-shared-services-prism