我有一个在构造函数中有一些参数的类。
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 Service Provider。使用非静态类,您可以注入此接口并将其用于向.NET Core Service Provider请求注册的服务,例如
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在创建服务时使用服务提供商将服务注入到您注册的服务/控制器等中。在这种情况下,您只是在做与手动相同的操作。
注意:您将需要注册您MyClass
的startup.cs
服务提供商将被注入的构造。例如:
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
我们前面提到的接口的实现。
调用GetService
可以在Configure
方法中的任何地方进行。它不必一开始就正确。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句