Configuring the Host Builder
To enable Unity as the dependency injection framework for SuperSocket, begin by installing the Unity.Microsoft.DependencyInjection NuGet package. During the initialization of the server host, apply the UseUnityServiceProvider extension method to the IHostBuilder. This bridges the SuperSocket lifecycle with the Unity container, allowing dependencies to be resolved across the application.
IHost socketHost = SuperSocketHostBuilder.Create<DataPacket, TransmissionFilter>()
.UseUnityServiceProvider(unityContainer)
.UseSession<CustomSession>()
.UseCommand(commandConfig =>
{
commandConfig.AddCommand<ProcessDataCommand>();
})
.ConfigureLogging((hostContext, loggingFactory) =>
{
loggingFactory.SetMinimumLevel(LogLevel.Information);
})
.Build();Registering Application Services
Services required by the application logic should be registered within the container. In a Prism-based application, this is typically handled in the RegisterTypes method. Once registered, these services can be injected into SuperSocket components.
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<ILoggingService, FileLoggingService>();
containerRegistry.RegisterSingleton<IServerManager, SocketServerManager>();
}Injecting Dependencies into AppSession
With the Unity service provider configured, constructor injection becomes available for custom session classes. The following example demonstrates injecting a logging service into a derived AppSession to monitor connection events.
public class CustomSession : AppSession
{
private readonly ILoggingService _loggingService;
public CustomSession(ILoggingService loggingService)
{
_loggingService = loggingService;
}
protected override async ValueTask OnSessionConnectedAsync()
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
_loggingService.LogInfo($"{timestamp} - Session Connected: {RemoteEndPoint}");
await Task.CompletedTask;
}
protected override async ValueTask OnSessionClosedAsync(CloseEventArgs eventArgs)
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
_loggingService.LogInfo($"{timestamp} - Session Closed: {RemoteEndPoint}. Reason: {eventArgs.Reason}");
await Task.CompletedTask;
}
}