简体   繁体   中英

What is the best way to create shared serial port access in Prism 6 multimodule WPF MVVM application?

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:

  1. Shell (main window) project.
  2. Multiple Prism modules projects.
  3. ClassLibrary project with global access from all these Prism modules and from Shell.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM