在我使用
的控制台应用中我有一个引擎类需要 NotificationHub ,而NotificationHub需要 ClientWriter 才能运行。我设法设置依赖项,但似乎引擎无法直接使用集线器。后来我发现集线器引擎的使用方式与客户端连接的不同。这是我的文件:
Engine.cs
public class Engine
{
private readonly NotificationHub _hub;
private readonly Timer _timer;
public Engine(NotificationHub hub)
{
_hub = hub;
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += (o, arg) =>
{
_timer.Enabled = false;
Inform(arg.SignalTime.ToString());
_timer.Enabled = true;
};
_timer.Start();
}
public void Inform(string str)
{
try
{
var ctx = GlobalHost.ConnectionManager.GetHubContext("notification");
ctx.Clients.All.Notify($"{str} ====="); //works why?
_hub.Inform(str); // does not work why?
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
NotificationHub.cs
public class NotificationHub : Hub
{
ClientWriter _writer;
public NotificationHub(ClientWriter writer)
{
_writer = writer;
}
public override Task OnConnected()
{
Console.WriteLine($"connected {Context.ConnectionId}");
Clients.All.Notify($"{Context.ConnectionId} has joined");
return base.OnConnected();
}
public DateTime Inform(string msg)
{
_writer.Received(msg);
return DateTime.Now;
}
}
ClientWriter.cs
public class ClientWriter
{
public void Received(string arg)
{
Console.WriteLine(arg);
}
}
HubActivator
class SimpleInjectorSignalRHubActivator : IHubActivator
{
Container _container;
public SimpleInjectorSignalRHubActivator(Container container)
{
_container = container;
}
public IHub Create(HubDescriptor descriptor)
{
return _container.GetInstance(descriptor.HubType) as IHub;
}
}
Program.cs的
static void Main(string[] args)
{
var _container = new Container();
_container.RegisterSingleton<NotificationHub>();
_container.RegisterSingleton<Engine>();
_container.RegisterSingleton<ClientWriter>();
var options = new StartOptions();
options.Urls.Add("http://localhost:12345");
using (var server = WebApp.Start(options, (app) =>
{
var activator = new SimpleInjectorSignalRHubActivator(_container);
GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => activator);
GlobalHost.DependencyResolver.Register(typeof(NotificationHub), () => _container.GetInstance<NotificationHub>());
app.RunSignalR(new HubConfiguration { EnableDetailedErrors = true });
app.UseWelcomePage();
}))
{
var ctx = GlobalHost.ConnectionManager.GetHubContext("notification");
var engine = _container.GetInstance<Engine>();
engine.Inform("Engine has started");
Console.ReadLine();
}
}
我做错了什么。为什么引擎无法发送给客户