从领域服务和应用层访问 SignalR

2024-03-18

这直接关系到从应用程序服务层调用 SignalR Hub https://stackoverflow.com/questions/55472303/is-calling-a-signalr-hub-from-the-application-service-layer-a-bad-practice-in-as在 ASP.NET Boilerplate .NET Core 版本中。根据解决方案,SignalR hub 实现应该在 Web 层完成。但项目的依赖结构是这样的:

  • 应用程序取决于Domain.Core
  • Web.Core取决于应用程序
  • Web.Host依赖于取决于Web.Core

两个问题:

  1. 为了能够使用Hub同时Domain.Core和应用程序项目,我应该如何连接它们?如果我在应用程序层中使用空模式定义接口,我可以在Web.Core。但是我不能在域服务中使用它(例如EventBus).

  2. 我可以将整个 SignalR 中心移动到新模块并从应用程序、域和 Web 层引用它吗?


  1. 为了能够使用Hub同时Domain.Core和应用程序项目,我应该如何连接它们?

域层:

  • IMyNotifier界面
  • NullMyNotifier空实现
public interface IMyNotifier
{
    Task SendMessage(IUserIdentifier user, string message);
}

public class NullMyNotifier : IMyNotifier
{
    public static NullMyNotifier Instance { get; } = new NullMyNotifier();

    private NullMyNotifier()
    {
    }

    public Task SendMessage(IUserIdentifier user, string message)
    {
        return Task.FromResult(0);
    }
}

网络层:

  • SignalR 集线器实现,例如MyChatHub https://aspnetboilerplate.com/Pages/Documents/SignalR-AspNetCore-Integration#your-signalr-code
  • SignalRMyNotifier具体实施
public class SignalRMyNotifier : IMyNotifier, ITransientDependency
{
    private readonly IOnlineClientManager _onlineClientManager;
    private readonly IHubContext<MyChatHub> _hubContext;

    public SignalRMyNotifier(
        IOnlineClientManager onlineClientManager,
        IHubContext<MyChatHub> hubContext)
    {
        _onlineClientManager = onlineClientManager;
        _hubContext = hubContext;
    }

    public async Task SendMessage(IUserIdentifier user, string message)
    {
        var onlineClients = _onlineClientManager.GetAllByUserId(user);
        foreach (var onlineClient in onlineClients)
        {
            var signalRClient = _hubContext.Clients.Client(onlineClient.ConnectionId);
            await signalRClient.SendAsync("getMessage", message);
        }
    }
}

在引用域层的任何层中的用法:

public class MyDomainService : DomainService, IMyManager
{
    public IMyNotifier MyNotifier { get; set; }

    public MyDomainService()
    {
        MyNotifier = NullMyNotifier.Instance;
    }

    public async Task DoSomething()
    {
        // Do something
        // ...

        var hostAdmin = new UserIdentifier(null, 1);
        var message = "Something done";
        await MyNotifier.SendMessage(hostAdmin, message);
    }
}
  1. 我可以将整个 SignalR 中心移动到新模块并从应用程序、域和 Web 层引用它吗?

您可以,但是包含 SignalR hub(以及您的应用程序和域层)的新模块将取决于Microsoft.AspNetCore.SignalR,这取决于Microsoft.AspNetCore.Http.Connections。领域层不应该依赖于Http.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从领域服务和应用层访问 SignalR 的相关文章

随机推荐