Skip to content

Commit

Permalink
Merge pull request #18 from TwitchLib/feature/non-di-constructor
Browse files Browse the repository at this point in the history
Add non DI constructor
  • Loading branch information
Syzuna authored Jun 1, 2023
2 parents 38d6070 + cd48319 commit 72088d1
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static IHostBuilder CreateHostBuilder(string[] args) =>
services.AddLogging();
services.AddTwitchLibEventSubWebsockets();

services.AddHostedService<WebsocketHostedService>();
services.AddHostedService<WebsocketHostedServiceWithoutDI>();
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TwitchLib.EventSub.Websockets.Core.EventArgs;
using TwitchLib.EventSub.Websockets.Core.EventArgs.Channel;

namespace TwitchLib.EventSub.Websockets.Example.NetStandard
{
public class WebsocketHostedServiceWithoutDI : IHostedService
{
private readonly ILogger<WebsocketHostedService> _logger;
private readonly EventSubWebsocketClient _eventSubWebsocketClient;

public WebsocketHostedServiceWithoutDI(ILogger<WebsocketHostedService> logger, ILoggerFactory loggerFactory)
{
_logger = logger;
_eventSubWebsocketClient = new EventSubWebsocketClient(loggerFactory);

_eventSubWebsocketClient.WebsocketConnected += OnWebsocketConnected;
_eventSubWebsocketClient.WebsocketDisconnected += OnWebsocketDisconnected;
_eventSubWebsocketClient.WebsocketReconnected += OnWebsocketReconnected;
_eventSubWebsocketClient.ErrorOccurred += OnErrorOccurred;

_eventSubWebsocketClient.ChannelFollow += OnChannelFollow;
}

public async Task StartAsync(CancellationToken cancellationToken)
{
await _eventSubWebsocketClient.ConnectAsync();
}

public async Task StopAsync(CancellationToken cancellationToken)
{
await _eventSubWebsocketClient.DisconnectAsync();
}

private async Task OnErrorOccurred(object sender, ErrorOccuredArgs e)
{
_logger.LogError($"Websocket {_eventSubWebsocketClient.SessionId} - Error occurred!");
}

private async Task OnChannelFollow(object sender, ChannelFollowArgs e)
{
var eventData = e.Notification.Payload.Event;
_logger.LogInformation($"{eventData.UserName} followed {eventData.BroadcasterUserName} at {eventData.FollowedAt}");
}

private async Task OnWebsocketConnected(object sender, WebsocketConnectedArgs e)
{
_logger.LogInformation($"Websocket {_eventSubWebsocketClient.SessionId} connected!");

if (!e.IsRequestedReconnect)
{
// subscribe to topics
}
}

private async Task OnWebsocketDisconnected(object sender, EventArgs e)
{
_logger.LogError($"Websocket {_eventSubWebsocketClient.SessionId} disconnected!");

// Don't do this in production. You should implement a better reconnect strategy
while (!await _eventSubWebsocketClient.ReconnectAsync())
{
_logger.LogError("Websocket reconnect failed!");
await Task.Delay(1000);
}
}

private async Task OnWebsocketReconnected(object sender, EventArgs e)
{
_logger.LogWarning($"Websocket {_eventSubWebsocketClient.SessionId} reconnected");
}
}
}
38 changes: 36 additions & 2 deletions TwitchLib.EventSub.Websockets/EventSubWebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using TwitchLib.EventSub.Websockets.Client;
using TwitchLib.EventSub.Websockets.Core.EventArgs;
using TwitchLib.EventSub.Websockets.Core.EventArgs.Channel;
Expand Down Expand Up @@ -266,6 +268,7 @@ public class EventSubWebsocketClient
private Dictionary<string, Action<EventSubWebsocketClient, string, JsonSerializerOptions>> _handlers;

private readonly ILogger<EventSubWebsocketClient> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IServiceProvider _serviceProvider;

private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
Expand Down Expand Up @@ -300,6 +303,37 @@ public EventSubWebsocketClient(ILogger<EventSubWebsocketClient> logger, IEnumera
_reconnectRequested = false;
}

/// <summary>
/// Instantiates an EventSubWebsocketClient used to subscribe to EventSub notifications via Websockets.
/// </summary>
/// <param name="loggerFactory">LoggerFactory used to construct Loggers for the EventSubWebsocketClient and underlying classes</param>
public EventSubWebsocketClient(ILoggerFactory loggerFactory = null)
{
_loggerFactory = loggerFactory;

_logger = _loggerFactory != null
? _loggerFactory.CreateLogger<EventSubWebsocketClient>()
: NullLogger<EventSubWebsocketClient>.Instance;

_websocketClient = _loggerFactory != null
? new WebsocketClient(_loggerFactory.CreateLogger<WebsocketClient>())
: new WebsocketClient();

_websocketClient.OnDataReceived += OnDataReceived;
_websocketClient.OnErrorOccurred += OnErrorOccurred;

var handlers = typeof(INotificationHandler)
.Assembly.ExportedTypes
.Where(x => typeof(INotificationHandler).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.Select(Activator.CreateInstance).Cast<INotificationHandler>()
.ToList();

PrepareHandlers(handlers);

_reconnectComplete = false;
_reconnectRequested = false;
}

/// <summary>
/// Connect to Twitch EventSub Websockets
/// </summary>
Expand Down Expand Up @@ -357,7 +391,7 @@ private async Task<bool> ReconnectAsync(Uri url)

var reconnectClient = _serviceProvider != null
? _serviceProvider.GetRequiredService<WebsocketClient>()
: new WebsocketClient(null);
: new WebsocketClient(_loggerFactory?.CreateLogger<WebsocketClient>());

reconnectClient.OnDataReceived += OnDataReceived;
reconnectClient.OnErrorOccurred += OnErrorOccurred;
Expand Down Expand Up @@ -403,7 +437,7 @@ private async Task<bool> ReconnectAsync(Uri url)

_websocketClient = _serviceProvider != null
? _serviceProvider.GetRequiredService<WebsocketClient>()
: new WebsocketClient(null);
: new WebsocketClient(_loggerFactory?.CreateLogger<WebsocketClient>());

_websocketClient.OnDataReceived += OnDataReceived;
_websocketClient.OnErrorOccurred += OnErrorOccurred;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using TwitchLib.EventSub.Websockets.Client;
using TwitchLib.EventSub.Websockets.Core.Handler;

Expand Down Expand Up @@ -42,7 +44,7 @@ private static IServiceCollection AddNotificationHandlers(this IServiceCollectio
public static IServiceCollection AddTwitchLibEventSubWebsockets(this IServiceCollection services)
{
services.TryAddTransient<WebsocketClient>();
services.TryAddSingleton<EventSubWebsocketClient>();
services.TryAddSingleton(x => new EventSubWebsocketClient(x.GetRequiredService<ILogger<EventSubWebsocketClient>>(), x.GetRequiredService<IEnumerable<INotificationHandler>>(), x.GetRequiredService<IServiceProvider>(), x.GetRequiredService<WebsocketClient>()));
services.AddNotificationHandlers(typeof(INotificationHandler));
return services;
}
Expand Down

0 comments on commit 72088d1

Please sign in to comment.