如何在我的模块中使用 BinaryConnection 发送和接收数据

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

我有一个自定义模块 MyModule,此插件中有一个自定义插件 MyPlugin 我想通过 BinaryConnection 发送和接收数据。 这是我的代码的简化版本

[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();
    }
}

当我启动运行时时,我得到一个 NullReferenceException,因为 ConnectionFactory 没有被注入。我的错误在哪里?

手动使用 the binary connection in your module you can either instantiate TcpClientConnection and TcpListenerConnection 或使用您的模块 DI-Container,正如您已经尝试过的那样,我会推荐。

要在您的模块中使用它,您需要将 register/load 类 放入您的容器中。看看资源管理registers them是如何工作的。在您的 OnInitialize 中,您需要:

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

然后您可以在您的配置中添加一个 BinaryConnectionConfig 条目并用 [PluginConfigs(typeof(IBinaryConnection), false)] 装饰到 select 套接字以及 MaintenanceWeb 中的 Client/Server 或使用派生的直接输入 TcpClientConfig/TcpListenerConfig

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

在您的插件中,您可以注入 IBinaryConnectionFactoryModuleConfig 来创建连接。

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:在OnStartreturns实例中解析工厂,你不用也没有必要。不要将 Resolve(查找已注册的实现并创建实例)与 Register.

混淆