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:
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/signalr");
});
}
...
Question: Could I pass logger to ChatHub
from as I do it with another services like this: 传递到ChatHub
吗?
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
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() { } public async Task SendMessage(string user, string 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, ...);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.