[英]How to pass logger into SignalR hub on server side in ASP.NET Core application
I have ASP.NET Core application with React client. 我有带有React客户端的ASP.NET Core应用程序。 I have SignalR messaging between server and client.
我在服务器和客户端之间有SignalR消息传递。
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
传递到ChatHub
吗?
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));
}
Could I pass logger to ChatHub from Startup.cs as I do it with another services like this
我可以像其他服务一样将记录器从Startup.cs传递到ChatHub吗?
I'm not sure why you want to pass a logger instance to ChatHub
within Startup.cs
. 我不确定为什么要在
Startup.cs
ChatHub
记录器实例传递给ChatHub
。 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. 在启动过程中,您不必手动将记录器实例传递到
ChatHub
中。 Typically that will be considered as a bad practice. 通常,这将被视为不良做法。 Just declare a dependency and let DI container inject it .
只需声明一个依赖项,然后让DI容器注入它 。
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>
并更改您的
ChatHub
构造函数以接受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: 如果确实要自定义Converter的初始化,则可以如下进行:
services.AddSingleton<Converter>(sp => {
var logger = sp.GetRequiredService<ILogger<Converter>>();
// add more service or dependencies manually ...
return new Converter(logger, ...);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.