radu-matei/websocket-manager

dependency injection in the subclass inherits from WebsocketHandler

Closed this issue · 3 comments

Hi,

it is possible to inject dependencies in the websocket handler ?

Hi!
Sure, the handler is just another class, meaning you should be able to inject dependencies as usual in ASP.NET Core.

Please let us know if this doesn't work as intended :)

Radu M

I try to use the entityframework context as a dependency and it throws me the next exception:

System.InvalidOperationException: 'Cannot consume scoped service 'app.DataContext' from singleton 'app.WebSocketService'.'

My Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddCors(options => options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));
        services.AddOptions();

        services.AddSingleton<IConfiguration>(Configuration);
        services.AddDbContext<DataContext>(options => {
            options.UseSqlServer(Configuration.GetConnectionString("Test"));
        });

        services.AddWebSocketManager();
    }

    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.UseWebSockets();
        app.MapWebSocketManager("/service", serviceProvider.GetService<WebSocketService>());

        app.UseMvc();
        app.UseCors("AllowAllOrigins");
    }
}

My Subclass

public partial class WebSocketService : WebSocketHandler
{
    private readonly DataContext _context;

    public WebSocketService(WebSocketConnectionManager webSocketConnectionManager, DataContext context)
        : base(webSocketConnectionManager)
    {
        _context = context;
    }

    public override async Task OnConnected(WebSocket socket)
    {
        await base.OnConnected(socket);
    }

    public override async Task OnDisconnected(WebSocket socket)
    {
        await base.OnDisconnected(socket);
    }
}
JanBN commented

Hi, did you solve this problem ?