【发布时间】:2019-03-29 20:02:00
【问题描述】:
我有一个Console Application,我正在尝试订阅一个SignalR 集线器。
查看互联网上的所有示例,我看到所有人都使用HubConnection 来做到这一点。
问题是我认为它们都已被弃用,因为在他们的情况下constructor 需要url,而在文档中需要IConnectionFactory 和ILoggerFactory。
服务器
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddCors(o =>
o.AddPolicy("CorsPolicty", b => b.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseDeveloperExceptionPage();
app.UseSignalR(r => r.MapHub<MyHub>("/myhub"));
}
}
public class MyHub:Hub {
public async Task SendMessage(string user,string message) {
await this.Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
客户
所以HubConnection 看起来不像MSDN 示例中的那样,我也看过HubConnectionBuilder 类,在所有示例中都有WithUrl 扩展名,而实际上它有一个IServiceCollection可以添加服务。
class ConcreteContext : ConnectionContext {
public override string ConnectionId { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override IFeatureCollection Features => throw new NotImplementedException();
public override IDictionary<object, object> Items { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override IDuplexPipe Transport { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
class Factory : IConnectionFactory {
public Task<ConnectionContext> ConnectAsync(TransferFormat transferFormat, CancellationToken cancellationToken = default(CancellationToken)) {
var context = new ConcreteContext();
return Task.FromResult(context as ConnectionContext);
}
public Task DisposeAsync(ConnectionContext connection) {
throw new NotImplementedException();
}
}
class Program {
static void Main(string[] args) {
//try 1
var builder = new HubConnectionBuilder().Build(); //no withUrl extensions
//try 2
var factory = new Factory();
var hub = new HubConnection(factory,); //needs IConnectionFactory and IHubProtocol and ILoggerFactory
}
我不敢相信我必须实现所有膨胀才能开始连接。如何连接到集线器?
如果我不得不为一件事写这么多,我可能会考虑回到原始websockets。
【问题讨论】: