在SuperSocket中使用Unity注入


本文環境為.Net5 + WPF + Prism + Unity + SuperSocket 2.0.0-beta.10,介紹了在WPF中如何對SuperSocket 2.0進行依賴注入的方法。

至於如何在WPF中集成SuperSocket 2.0,參考“在WPF中集成SuperSocket 2.0”。

1、為服務器主機添加Unity支持

首先要通過NuGet添加Unity.Microsoft.DependencyInjection依賴。

然后在創建服務器主機時,為IHostBuilder接口使用UseUnityServiceProvider擴展方法,以支持使用Unity依賴注入。

由於使用IOC方式創建SocketServerService對象,因此IUnityContainer對象可以直接在構造函數中注入。

//創建宿主:用Package類型和PipelineFilter類型創建SuperSocket宿主。
_host = SuperSocketHostBuilder.Create<MyPackageInfo, MyPipelineFilter>()
    //注入Service
    .UseHostedService<MyService<MyPackageInfo>>()
    //注入Session
    .UseSession<MySession>()
    //注入命令
    .UseCommand((commandOptions) =>
    {
        commandOptions.AddCommand<MyCommand>(); //數據命令
    })
    //啟用Session容器
    .UseInProcSessionContainer()
    //配置日志
    .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.SetMinimumLevel(LogLevel.Warning); })
    .UseUnityServiceProvider(container)
    .Build();

2、注入ISocketServerService

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    //注冊單例服務
    containerRegistry.RegisterSingleton<ILogService, LogService>();
    containerRegistry.RegisterSingleton<ISocketServerService, SocketServerService>();
}

3、在SuperSocket相關類中注入服務

以AppSession為例說明如何進行服務注入。

public class MySession : AppSession
{
    private readonly ILogService _logService;

    public MySession(ILogService logService)
    {
        _logService = logService;
    }

    protected override async ValueTask OnSessionConnectedAsync()
    {
        _logService?.Info($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} " +
                          $@"New Session connected: {RemoteEndPoint}.");
        await Task.Delay(0);
    }

    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        _logService?.Info($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} " +
                          $@"Session {RemoteEndPoint} closed: {e.Reason}.");
        await Task.Delay(0);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM