问题
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