本文介绍了如何在ASP.NET Core应用程序中将记录器传递到服务器端的SignalR集线器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有React客户端的ASP.NET Core应用程序.我在服务器和客户端之间有SignalR消息传递.

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");
        });
    }
    ...

问题:我可以像使用其他服务一样,通过 Startup.cs 将记录器传递给 ChatHub 吗?

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));
        }

推荐答案

我不确定为什么要将记录器实例传递给 Startup.cs 中的 ChatHub .但是据我所知,您总是可以在需要时注入所需的依赖项.在启动过程中,您不必手动将记录器实例传递到 ChatHub 中.通常,这将被视为不良做法.只需声明一个依赖项并让 DI 容器注入它.

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<Converter>();   // DI will new it and inject logger for you

并更改您的 ChatHub 构造函数以接受 ILogger< ChatHub>

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);
    }
}


如果您要自定义Converter的初始化,则可以按照以下步骤进行操作:


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, ...);
});

这篇关于如何在ASP.NET Core应用程序中将记录器传递到服务器端的SignalR集线器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 04:41