Reputation: 151
For a long time I've periodically searched information about creating shared access to serial port in multimodule Prism MVVM application but there are not any good papers. Therefore I address to you here. I develop C# WPF MVVM Prism 6 application using MS VS 2015 Professional in Windows 10 64-bites OS. The solution is consisting of:
I need shared access to one SerialPort instance from all Prism modules in the application for communication with outer device. What is the best approach to solve this problem about shared serial port? If I create SerialPort as public static member and put it in one of the static class in the above mentioned ClassLibrary, will this way be the best one? Or put such SerialPort instance in shared service will be the best? Or any other solutions about shared SerialPort instance have place? So please advice me how to define globally accessed shared SerialPort in multimodule Prism 6 WPF MVVM application?
Upvotes: 0
Views: 616
Reputation: 10863
Create an interface for the serial port in the shared class library, implement it in one of the modules, register it as singleton and use it wherever you like:
// in the class lib:
public interface ISerialPortService
{
void SendSomething();
}
// in a one of the modules:
public class OneModule : IModule
{
public OneModule( IUnityContainer container )
{
_container = container;
}
public void Initialize()
{
_container.RegisterType<ISerialPortService, MySerialPortImplementation>( new ContainerControlledLifetimeManager() );
}
private readonly IUnityContainer _container;
}
internal class MySerialPortImplementation : ISerialPortService
{
// ... implement all the needed functionality ...
}
// somewhere else...
internal class SerialPortConsumer
{
public SerialPortConsumer( ISerialPortService serialPort )
{
_serialPort = serialPort;
}
public void SomeMethod()
{
_serialPort.SendSomething();
}
private readonly ISerialPortService _serialPort;
}
I'd strongly advise against a static class, because it only makes your application less flexible and you gain nothing in comparison to a service.
Upvotes: 0