How to pass logger into SignalR hub on server side in ASP.NET Core application

怎甘沉沦 提交于 2021-01-29 11:37:27

问题


I have ASP.NET Core application with React client. I have SignalR messaging between server and client.

I have the following code on server side:

Startup.cs

    ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/signalr");
        });
    }
    ...

Question: Could I pass logger to ChatHub from Startup.cs as I do it with another services like this:

Startup.cs

        private readonly ILogger _log;

        public Startup(IHostingEnvironment env, ILogger<Startup> log)
        {
            _log = log;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Converter(_log));
        }

回答1:


Could I pass logger to ChatHub from Startup.cs as I do it with another services like this

I'm not sure why you want to pass a logger instance to ChatHub within Startup.cs. But As far as I know, you could always inject the required dependencies when you need. You don't have to manually pass a logger instance into ChatHub during startup. Typically that will be considered as a bad practice. Just declare a dependency and let DI container inject it.

services.AddSingleton(new Converter(_log));
services.AddSingleton<Converter>();   // DI will new it and inject logger for you

And also change your ChatHub constructor to accept a ILogger<ChatHub>

public class ChatHub : Hub
{
    private readonly ILogger<ChatHub> _logger;

    public ChatHub(ILogger<ChatHub> logger)
    {
        this._logger = logger;
    }

    public async Task SendMessage(string user, string message)
    {
        this._logger.LogInformation($"send message to client\r\n {user}\t{message}");
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

If you do want to custom the initialization of Converter, you could make it as below:

services.AddSingleton<Converter>(sp => {
    var logger = sp.GetRequiredService<ILogger<Converter>>();
    // add more service or dependencies manually ...
    return new Converter(logger, ...);
});


来源:https://stackoverflow.com/questions/56689026/how-to-pass-logger-into-signalr-hub-on-server-side-in-asp-net-core-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!