MrE*_*een 0 c# dependency-injection asp.net-core asp.net-core-signalr
如果在这个问题上花了很多时间,我发现了很多不同的策略,但没有一个对我有用。(此代码只是概念的证明。)
我使用 Asp.net core 2.1(在 .Net Framwork 4.7.2 上)进行了以下设置:
我制作了一个信号集线器,它有一种发送数字的方法:
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace TestRandomNumberSignalR
{
public class TestHub : Hub
{
public async Task SendRandomNumber(int number)
{
await Clients.All.SendAsync("ReceiveRandomBumber", number);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还创建了一个每 3 秒更新一个随机数并将其添加为单例的类:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TestRandomNumberSignalR
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new UpdateRandomNumber());
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/testHub");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是随机数类:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TestRandomNumberSignalR
{
public class UpdateRandomNumber
{
private bool _continue = true;
public UpdateRandomNumber()
{
var task = new Task(() => RandomNumberLoop(),
TaskCreationOptions.LongRunning);
task.Start();
}
private void RandomNumberLoop()
{
Random r = new Random();
while (_continue)
{
Thread.Sleep(3000);
int number = r.Next(0, 100);
Console.WriteLine("The random number is now " + number);
// Send new random number to connected subscribers here
// Something like TestHub.SendRandomNumber(number);
}
}
public void Stop()
{
_continue = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在从这个类(正如我在评论中所写)我想使用 SignalR 发送新的随机数。只有如何在那里获取集线器上下文?
此外,我希望能够从控制器内访问类上的 Stop() 方法,我该如何访问?
我现在这是一个很好讨论的主题,但我仍然无法在任何地方找到可行的解决方案。希望您能够帮助我。
编辑
问题 1
虽然随机循环现在开始(非常感谢rasarasha),但仍然存在一些问题。我现在无法将正确的 UpdateRandomNumber 注入控制器。假设我希望能够停止调用 UpdateRandomNumber.Stop() 方法的循环,如何将 UpdateRandomNumber 单例注入控制器。我尝试创建一个界面:
public interface IUpdateRandomNumber
{
void Stop();
}
Run Code Online (Sandbox Code Playgroud)
更改 RandomNumber 方法以实现此目的:
public class UpdateRandomNumber : IUpdateRandomNumber
{
private bool _continue = true;
private IHubContext<TestHub> testHub;
public UpdateRandomNumber(IHubContext<TestHub> testHub)
{
this.testHub = testHub;
var task = new Task(() => RandomNumberLoop(),
TaskCreationOptions.LongRunning);
task.Start();
}
private void RandomNumberLoop()
{
Random r = new Random();
while (_continue)
{
Thread.Sleep(3000);
int number = r.Next(0, 100);
Console.WriteLine("The random number is now " + number);
// Send new random number to connected subscribers here
// Something like TestHub.SendRandomNumber(number);
}
}
public void Stop()
{
_continue = false;
}
}
Run Code Online (Sandbox Code Playgroud)
并更改添加单例方法,以便使用该接口:
services.AddSingleton<IUpdateRandomNumber>(provider =>
{
var hubContext = provider.GetService<IHubContext<TestHub>>();
var updateRandomNumber = new UpdateRandomNumber(hubContext);
return updateRandomNumber;
});
Run Code Online (Sandbox Code Playgroud)
我现在可以使用停止随机数循环的方法创建一个控制器:
[Route("api/[controller]")]
[ApiController]
public class RandomController : ControllerBase
{
private readonly IUpdateRandomNumber _updateRandomNumber;
public RandomController(IUpdateRandomNumber updateRandomNumber)
{
_updateRandomNumber = updateRandomNumber;
}
// POST api/random
[HttpPost]
public void Post()
{
_updateRandomNumber.Stop();
}
Run Code Online (Sandbox Code Playgroud)
但是,此实现将阻止循环再次启动。那么如何从控制器访问 rondomnumber 单例呢?
问题2
从我的 UpdateRandomNumber 类,我现在可以调用:
testHub.Clients.All.SendAsync("ReceiveRandomBumber", number);
Run Code Online (Sandbox Code Playgroud)
但是为什么我要在我的 testhub 中创建该方法:
public async Task SendRandomNumber(int number)
{
await Clients.All.SendAsync("ReceiveRandomBumber", number);
}
Run Code Online (Sandbox Code Playgroud)
在集线器中创建方法并直接调用它们会更方便。这能做到吗?
您可以使用构造函数注入将 TestHub 注入控制器。因为它已经在 DI 容器中注册了。
public class UpdateRandomNumber
{
private bool _continue = true;
private IHubContext<TestHub> testHub;
private Task randomNumberTask;
public UpdateRandomNumber(IHubContext<TestHub> testHub)
{
this.testHub=testHub;
randomNumberTask = new Task(() => RandomNumberLoop(),
TaskCreationOptions.LongRunning);
randomNumberTask.Start();
}
private async void RandomNumberLoop()
{
Random r = new Random();
while (_continue)
{
Thread.Sleep(3000);
int number = r.Next(0, 100);
Console.WriteLine("The random number is now " + number);
// Send new random number to connected subscribers here
await testHub.Clients.All.SendAsync($"ReceiveRandomNumber", number);
}
}
public void Stop()
{
_continue = false;
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(provider =>
{
var hubContext = provider.GetService<IHubContext<TestHub>>();
var updateRandomNumber = new UpdateRandomNumber(hubContext);
return updateRandomNumber;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var updateRandonNumber = app.ApplicationServices.GetService<UpdateRandomNumber>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/testHub");
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2244 次 |
| 最近记录: |