# SignalR.Modules
This sample shows how to build SignalR modules with a shared connection using a C# Source Generator.
Read more about the background in my blog post "[SignalR modules with a shared connection using a C# Source Generator](https://guidnew.com/en/blog/signalr-modules-with-a-shared-connection-using-a-csharp-source-generator/)".
The concept is based on the idea of organizing multiple hub methods in partial classes within the same project.
But instead of putting everything in one project, SignalR modules can live in separate projects or NuGet packages.
The partial classes get then generated using a C# Source Generator.
This is an overview of how it works:
![SignalR.Modules Overview](SignalRModulesOverview.drawio.png "SignalR.Modules Overview")
## Create a module hub
To create a module hub, a reference to the SignalR.Modules project is needed. Then create a hub class as you would do with regular SignalR, but instead of `Hub` (or `Hub<T>`) use `ModuleHub` (or `ModuleHub<T>`) as base class.
```csharp
public class ChatHub : ModuleHub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
```
## Use a module hub
To use the module hub, create an ASP.NET Core project and add a reference to `SignalR.Modules` and `SignalR.Modules.Generator`.
```xml
<ProjectReference
Include="..\..SignalR.Modules.Generator\SignalR.Modules.Generator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<ProjectReference
Include="..\..SignalR.Modules\SignalR.Modules.csproj" />
```
Then add an SignalR entry hub that will be used by all module hubs.
```csharp
[SignalRModuleHub(typeof(ChatHub))]
[SignalRModuleHub(typeof(WeatherHub))]
[SignalRModuleHub(typeof(CounterHub))]
public partial class MainHub : ModulesEntryHub
{
}
```
The `ModulesEntryHub` derives from `Hub` and provides some helper methods to initialize the module hubs. We will see it later in the generated code.
The last step is to register all services and add an endpoint for the hub. I added an extension method that registers all module hubs that are added via the attribute.
```csharp
services.AddSignalRModules<MainHub>();
```
```csharp
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MainHub>("/hub");
// ...
});
```
## Strongly typed module hubs
SignalR allows us to define [strongly typed hubs](https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-5.0#strongly-typed-hubs) to avoid using magic strings. And you can do the same with SignalR modules by using `ModuleHub<T>`.
```csharp
public interface IWeatherClient
{
public Task ReceiveWeatherUpdate(IEnumerable<WeatherForecast> weatherForecast);
}
```
```csharp
public class WeatherHub : ModuleHub<IWeatherClient>
{
// ...
}
```
## Send messages from outside a hub
As you can [do it with regular SignalR hubs](https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0), you can send messages from outside a module hub as well. Instead of injecting `IHubContext<T>` you can inject `IModuleHubContext<T>`.
```csharp
public class ChatController : ControllerBase
{
private readonly IModuleHubContext<ChatHub> _hubContext;
public ChatController(IModuleHubContext<ChatHub> hubContext)
{
_hubContext = hubContext;
}
[HttpGet]
public ActionResult SendMessage(string user, string message)
{
_hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
return Ok();
}
}
```
When you have a strongly typed module hub, you can use `IModuleHubContext<WeatherHub, IWeatherClient>`.
## Using the ModuleHubClient
You can connect to the hub and start sending messages the same way as with any SignalR hub.
Optionally, you can use the `ModuleHubClient` class. It allows sharing the connection, prefixes all method names with the module hub name, and unsubscribes all handlers when it gets disposed.
To use it, create a client class per module hub that derives from the `ModuleHubClient`. For the `ChatHub` it’s just an empty class, but you could put more logic in it (see the `WeatherHubClient`).
```csharp
public class ChatHubClient : ModuleHubClient
{
}
```
Then add the clients to the service collection:
```csharp
builder.Services.AddSignalRModules("MainHub", sp => sp.GetRequiredService<NavigationManager>().ToAbsoluteUri("/hub"))
.AddModuleHubClient<ChatHubClient>()
.AddModuleHubClient<WeatherHubClient>()
.AddModuleHubClient<SignalRCounter>("CounterHub");
```
The `AddSignalRModules` method takes the name of the entry hub as the first parameter. The name is used internally as a key to share the connection. The second parameter can be the URL of the hub or an action to configure the SignalR `IHubConnectionBuilder`.
Then use `AddModuleHubClient` to add all the module hub clients that use the same entry hub. Per convention, the class name (without the Client suffix) is used to prefix all method names. Alternatively, it’s possible to pass the name as a parameter. By default, all clients get added as scoped services, but it’s possible to specify the `ServiceLifetime`.
没有合适的资源?快使用搜索试试~ 我知道了~
使用C#源生成器共享连接的模块化SignalR_C#_下载.zip
共95个文件
cs:44个
razor:10个
csproj:9个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 86 浏览量
2023-04-27
10:53:57
上传
评论
收藏 379KB ZIP 举报
温馨提示
使用C#源生成器共享连接的模块化SignalR_C#_下载.zip
资源推荐
资源详情
资源评论
收起资源包目录
使用C#源生成器共享连接的模块化SignalR_C#_下载.zip (95个子文件)
SignalR.Modules-main
.editorconfig 10KB
Directory.Build.props 1KB
src
SignalR.Modules.Generator
HubGenerator.cs 13KB
SignalR.Modules.Generator.csproj 422B
Properties
launchSettings.json 195B
SignalR.Modules.Client
ModuleHubClientExtensions.StreamAsChannelAsync.cs 22KB
SignalR.Modules.Client.csproj 249B
ModuleHubClientExtensions.SendAsync.cs 16KB
ModuleHubConnectionOptions.cs 219B
ModuleHubClientExtensions.cs 25KB
ModuleHubClientExtensions.StreamAsync.cs 17KB
IServiceCollectionExtensions.cs 2KB
ModuleHubClientBuilder.cs 2KB
ModuleHubClient.cs 7KB
ModuleHubClientExtensions.InvokeAsync.cs 16KB
ModuleHubConnectionManager.cs 6KB
ModuleHubClientExtensions.InvokeAsyncGeneric.cs 19KB
SignalR.Modules
SignalRModuleHubAttribute.cs 378B
ModuleHubTypedClients.cs 3KB
ModuleHubUntypedClients.cs 516B
SignalR.Modules.csproj 222B
ModuleHubContext{TEntryHub,TModuleHub,TModuleHubTyped}.cs 763B
ModuleHub{T}.cs 1KB
ClientProxy{T}.cs 283B
ModulesEntryHub.cs 1KB
ServiceCollectionExtensions.cs 2KB
ModuleHubTypedCallerClients.cs 837B
ClientProxy.cs 637B
ModuleHubUntypedCallerClients.cs 557B
IModuleHubContext.cs 231B
ModuleHubContext.cs 651B
ModuleHub.cs 3KB
IModuleHubContext{TModuleHub,TModuleHubTyped}.cs 332B
UntypedClientProxy.cs 567B
LICENSE 1KB
Analyzers.ruleset 743B
samples
Blazor
Client
wwwroot
css
bootstrap
bootstrap.min.css 152KB
bootstrap.min.css.map 611KB
open-iconic
font
css
open-iconic-bootstrap.min.css 9KB
fonts
open-iconic.woff 15KB
open-iconic.ttf 27KB
open-iconic.otf 21KB
open-iconic.svg 54KB
open-iconic.eot 28KB
ICON-LICENSE 1KB
FONT-LICENSE 4KB
README.md 3KB
app.css 861B
favicon.ico 5KB
index.html 710B
BlazorSignalR.Client.csproj 775B
Shared
NavMenu.razor 1KB
MainLayout.razor.css 1KB
SurveyPrompt.razor 507B
MainLayout.razor 377B
NavMenu.razor.css 1KB
Properties
launchSettings.json 921B
_Imports.razor 393B
SignalRCounter.cs 131B
Program.cs 1020B
ChatHubClient.cs 130B
App.razor 374B
Pages
Counter.razor 927B
FetchData.razor 2KB
Chat.razor 2KB
ChatBasic.razor 2KB
Index.razor 182B
WeatherModule.Client
ReceivedWeatherUpdateEventArgs.cs 325B
WeatherHubClient.cs 964B
WeatherModule.Client.csproj 348B
WeatherModule.Shared
WeatherModule.Shared.csproj 130B
WeatherForecast.cs 317B
WeatherModule.Server
WeatherUpdateHostedService.cs 2KB
WeatherHub.cs 2KB
WeatherModule.Server.csproj 334B
IWeatherClient.cs 267B
ChatModule.Server
ChatHub.cs 332B
ChatModule.Server.csproj 247B
Server
appsettings.Development.json 159B
Hubs
MainHub.cs 349B
Startup.cs 2KB
Properties
launchSettings.json 986B
Program.cs 767B
Controllers
ChatController.cs 976B
appsettings.json 180B
SignalRModules
CounterHub.cs 536B
BlazorSignalR.Server.csproj 790B
Pages
Error.cshtml 1KB
Error.cshtml.cs 754B
SignalRModulesOverview.drawio.png 130KB
StyleCop.json 855B
SignalR.Modules.sln 6KB
global.json 74B
.gitignore 6KB
README.md 5KB
共 95 条
- 1
资源评论
快撑死的鱼
- 粉丝: 1w+
- 资源: 9156
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功