【问题标题】:Class MessageAppService cannot have multiple base classes 'Hub' and 'AsyncCrudAppService'MessageAppService 类不能有多个基类“Hub”和“AsyncCrudAppService”
【发布时间】:2020-06-13 19:30:07
【问题描述】:

我正在使用带有 .NET Core 3.1 的 ASP.NET 样板。

我正在尝试将 SignalR 聊天记录保存到数据库中。问题是当我想创建AsyncCrudAppServiceHub 的子类时,出现以下文本错误:

类 MessageAppService 不能有多个基类 'Hub' 和 'AsyncCrudAppService'

这是我的代码:

namespace MyProject.ChatAppService
{
    public class MessageAppService : Hub, AsyncCrudAppService<Message, MessageDto, int, PagedAndSortedResultRequestDto, CreateMessageDto, UpdateMessageDto, ReadMessageDto>
    {
        private readonly IRepository<Message> _repository;

        private readonly IDbContextProvider<MyProjectDbContext> _dbContextProvider;
        private MyProjectPanelDbContext db => _dbContextProvider.GetDbContext();

        public MessageAppService(
            IDbContextProvider<MyProjectDbContext> dbContextProvider,
            IRepository<Message> repository)
            : base(repository)
        {
            _repository = repository;
            _dbContextProvider = dbContextProvider;
        }

        public  List<Dictionary<long, Tuple<string, string>>> InboxChat()
        {
            // The result will be List<userid, Tuple<username, latest message>>();
            List<Dictionary<long, Tuple<string, string>>> result = new List<Dictionary<long, Tuple<string, string>>>();

            List<User> listOfAllUsers = db.Set<User>().ToList();

            listOfAllUsers.ForEach((user) =>
            {
                try
                {
                    var dict = new Dictionary<long, Tuple<string, string>>();

                    var latestMessage = (from msg in db.Set<Message>() select msg)
                        .Where(msg => msg.CreatorUserId == user.Id && msg.receiverID == AbpSession.UserId)
                        .OrderByDescending(x => x.CreationTime)
                        .FirstOrDefault()
                        .Text.ToString();

                    dict.Add(user.Id, Tuple.Create(user.UserName, latestMessage));
                    result.Add(dict);
                }
                catch (Exception ex)
                {
                    new UserFriendlyException(ex.Message.ToString());
                }
            });

            return result;
        }

        public List<Message> getMessageHistory(int senderId)
        {
            return _repository.GetAll()
                .Where(x => x.CreatorUserId == senderId && x.receiverID == AbpSession.UserId )
                .ToList();
        }
    }
}

如何避免此错误?

更新

这是MyChatHub 代码,我想将其与AsyncCrudAppService 子类组合成一个类(我不知道这种方式是否正确,但这是我想到的!)。

public class MyChatHub : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public ILogger Logger { get; set; }

    public MyChatHub()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("getMessage", string.Format("User {0}: {1}", AbpSession.UserId, "the message that has been sent from client is "+message));
    }

    public async Task ReceiveMessage(string msg, long userId)
    {
        if (this.Clients != null)
        {
            await Clients.User(userId.ToString())
                .SendAsync("ReceiveMessage", msg, "From Server by userID ", Context.ConnectionId, Clock.Now);
        }
        else
        {
            throw new UserFriendlyException("something wrong");
        }
    }

    public override async Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
        Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId);
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        await base.OnDisconnectedAsync(exception);
        Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId);
    }
}    

【问题讨论】:

    标签: c# asp.net-core signalr-hub aspnetboilerplate asp.net-core-signalr


    【解决方案1】:

    您的AsyncCrudAppService 子类不能也不应该继承Hub

    相反,注入和使用类似于 ABP 的 SignalRRealTimeNotifierIHubContext&lt;MyChatHub&gt;

    public MessageAppService(
        IHubContext<MyChatHub> hubContext,
        IDbContextProvider<MyProjectDbContext> dbContextProvider,
        IRepository<Message> repository)
        : base(repository)
    {
        _dbContextProvider = dbContextProvider;
        _hubContext = hubContext;
        _repository = repository;
    }
    

    要向所有客户发送消息,请致电_hubContext.Clients.All.SendAsync(...)

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多