我有一个在构造函数中有一些参数的类。
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
传递给需要它的类。
发布于 2018-10-16 00:11:24
你的类需要是静态的吗?
当您在ConfigureServices
中注册您的类/服务时,它们将注册到.NET核心服务提供者。使用非静态类,您可以注入此接口,并使用它向.NET核心服务提供者请求已注册的服务。
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核心在创建服务时使用服务提供者将服务注入到已注册的服务/控制器等中。在这种情况下,您只需手动执行与其相同的操作即可。
注意:您需要在startup.cs
中注册您的MyClass
,以便将服务提供者注入到构造函数中。例如:
services.AddSingleton<MyClass>();
但是,现在您已经向服务提供商注册了MyClass
,您可以直接将依赖项注入到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
接口的一个实现。
Configure
方法中的任何地方都可以调用GetService
。它不一定要在一开始就进行。
https://stackoverflow.com/questions/52823437
复制相似问题