我有一个在构造函数中有一些参数的类。
public class ServerStatus
{
private int idserver;
private string des;
private string ipserver;
private int attemptfailded = 0;
public ServerStatus(int id, string description, string ip)
{
this.idserver = id;
this.des = description;
this.ipserver = ip;
}
... /* Other logic of this class: like notification management */
}
现在,我想在这个类中添加一个像这样的中心上下文的实例,并有一个使用这个中心上下文的方法。
public class ServerStatus
{
private readonly IHubContext<MyHub, ITypedHubClient> _hubContext;
private int idserver;
private string des;
private string ipserver;
private int attemptfailded = 0;
public ServerStatus(IHubContext<MyHub, ITypedHubClient> hubContext, int id, string description, string ip)
{
this.idserver = id;
this.des = description;
this.ipserver = ip;
_hubContext = hubContext;
}
...
public async Task SendMessageToClients()
{
await _hubContext.Clients.All.BroadcastMessage("Server",
"ServerDown");
}
}
特别是,我希望这个类可以在任何我想要的地方实例化,比如,如果我有另一个类实现了这个 ServerStatus
对象的列表,我需要从这个类调用构造函数。这是一个例子:
public static class MyClass
{
public static List<ServerStatus> servers = new List<ServerStatus>();
public static void initializeServers()
{
foreach (/* server I have in a Database */)
{
ServerStatus s = new ServerStatus (/* the hub context and the parameters of the server */)
servers.Add(s);
}
}
}
我的问题是:如何将这个 hubContext
添加到我的类中并在我需要的地方实例化对象。
请记住,我已经设置了所有 SignalR 库并且可以正常工作,但现在我不明白如何将 hubContext
传递给需要它的类。
最佳答案
你的类需要是静态的吗?
当您在 ConfigureServices
中注册您的类/服务时,它们会注册到 .NET Core 服务提供商。使用非静态类,您可以注入(inject)此接口(interface)并使用它来请求来自 .NET Core 服务提供者的注册服务,例如
public class MyClass
{
private readonly IServiceProvider _provider;
public MyClass(IServiceProvider provider)
{
_provider = provider;
}
public void InitializeServers()
{
foreach(/* server I have in database */)
{
var hub = _provider.GetService<IHubContext<MyHub, ITypedHubClient>>();
ServerStatus s = new ServerStatus(hub, ...);
}
}
}
您可以使用 IServiceProvider
检索已向其注册的任何服务,包括您的 IHubContext
。
在内部,.NET Core 在创建它们时使用服务提供者将服务注入(inject)到您注册的服务/ Controller 等中。在这种情况下,您只是在手动执行相同的操作。
注意:
您需要在 startup.cs
中注册您的 MyClass
,以便将服务提供者注入(inject)到构造函数中。例如:
services.AddSingleton<MyClass>();
但是,现在您已经向服务提供商注册了 MyClass
,您可以直接将依赖项注入(inject) MyClass
public class MyClass
{
private readonly IHubContext<MyHub, ITypedHubClient> _hubContext;
public MyClass(IHubContext<MyHub, ITypedHubClient> hubContext)
{
_hubContext = hubContext;
}
public void InitializeServers()
{
foreach(/* server I have in database */)
{
ServerStatus s = new ServerStatus(_hubContext, ...);
}
}
}
如果您想在启动时实例化此类,您可以在 Configure
方法中获取一个实例。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var myClass = app.ApplicationServices.GetService<MyClass>();
myClass.InitializeServers();
// the rest of the startup
...
}
ApplicationServices
是我们前面提到的 IServiceProvider
接口(interface)的实现。
对 GetService
的调用可以在 Configure
方法中的任何地方进行。它不必一开始就走对了。
关于c# - 如何使用其他构造函数的参数在类中检索 HubContext (SignalR)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52823437/