How to use BinaryConnection in my module to send and receive data

Viewed 36

I have a custom module MyModule with a custom plugin MyPlugin in this plugin I want to send and receive data via a BinaryConnection. Here is a simplified version of my code

[ServerModule(ModuleName)]
public class ModuleController : ServerModuleBase<ModuleConfig> 
{
    protected override void OnInitialize()
    {
        Container.LoadComponents<IMyPlugin>();
    }

    protected override void OnStart()
    {
        Container.Resolve<IBinaryConnectionFactory>();
        Container.Resolve<IMyPlugin>().Start(); 
    }
}
[Plugin(LifeCycle.Singleton, typeof(IMyPlugin), Name = PluginName)]
public class MyPlugin: IMyPlugin
{
    private IBinaryConnection _connection;

    public IBinaryConnectionFactory ConnectionFactory { get; set; }

    public IBinaryConnectionConfig Config { get; set; }

    public void Start()
    {
        _connection = ConnectionFactory.Create(Config, new MyMessageValidator());
        _connection.Received += OnReceivedDoSomething;
    
        _connection.Start();
    }
}

When I start the Runtime I get a NullReferenceException because the ConnectionFactory is not injected. Where is my mistake here?

1 Answers

To use the binary connection in your module you can either instantiate TcpClientConnection and TcpListenerConnection manually or use your modules DI-Container, as you already tried and I would recommend.

To use it in your module, you need to register/load the classes into your container. Take a look at how the Resource Management registers them. In your OnInitialize you need:

Container.Register<IBinaryConnectionFactory>(); // Register as factory
Container.LoadComponents<IBinaryConnection>(); // Register implementations

Then you can add either a BinaryConnectionConfig entry to your config and decorate with [PluginConfigs(typeof(IBinaryConnection), false)] to select Socket as well as Client/Server from the MaintenanceWeb or use the derived type TcpClientConfig/TcpListenerConfig directly.

public class ModuleConfig : ConfigBase
{
    [DataMember, PluginConfigs(typeof(IBinaryConnection), false)]
    public BinaryConnectionConfig ConnectionConfig { get; set; }
}

In you plugin you can then inject IBinaryConnectionFactory and ModuleConfig to create the connection.

public class MyPlugin: IMyPlugin
{
    private IBinaryConnection _connection;

    public IBinaryConnectionFactory ConnectionFactory { get; set; }

    public ModuleConfig Config { get; set; }

    public void Start()
    {
        _connection = ConnectionFactory.Create(Config.ConnectionConfig, new MyMessageValidator());
        _connection.Received += OnReceivedDoSomething;
    
        _connection.Start();
    }
}

PS: Resolving the factory in OnStart returns an instance, which you don't use and is unnecessary. Don't confuse Resolve(Find registered implementation and create instance) with Register.

Related