Как реализовать несколько уведомлений с помощью ASP.NET Boilerplate?

Я использую ASP.NET Boilerplate (с .NET Core). Я пытаюсь реализовать систему уведомлений, как указано в официальном документе в с несколькими уведомителями, но я обнаружил:

System.NullReferenceException: 'Ссылка на объект не установлена ​​на экземпляр объекта.'

Мой вопрос не относится к самому исключению. Я хочу знать, есть ли какие-либо настройки или настройки предварительных запросов, прежде чем реализовывать пример, или мой код что-то упускает:

public class MessageAppService: AsyncCrudAppService<Message, MessageDto, long, PagedAndSortedResultRequestDto, CreateMessageDto, UpdateMessageDto, ReadMessageDto>, IRealTimeNotifier, ITransientDependency
{
    private readonly IRepository<Message, long> _repository;

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

    IHubContext<MyChatHub> _hubContext; // This for online chat

    private readonly IEmailSender _emailSender;
    private readonly UserManager _userManager;

    private readonly INotificationSubscriptionManager _notificationSubscriptionManager;

    public MessageAppService(
        IDbContextProvider<MySystemDbContext> dbContextProvider,
        IRepository<Message, long> repository, 
        IHubContext<MyChatHub> hubContext /* This for online chat */,
        INotificationSubscriptionManager notificationSubscriptionManager,
        IEmailSender emailSender,
        UserManager userManager
    ) : base(repository)
    {
        _repository = repository;
        _dbContextProvider = dbContextProvider;
        _hubContext = hubContext; // This for online chat 
        _notificationSubscriptionManager = notificationSubscriptionManager;
        _emailSender = emailSender;
        _userManager = userManager;
    }

    public override async Task<MessageDto> CreateAsync(CreateMessageDto input)
    {
        var test = await base.CreateAsync(input);
        UserNotification userNotifications = new UserNotification();
        userNotifications.UserId = 10010;
        //
        userNotifications.Notification.TenantId = AbpSession.TenantId;
        userNotifications.Notification.NotificationName = "test";

        UserNotification[] notificationList = new UserNotification[1];
        notificationList[0] = userNotifications;
        await SendNotificationsAsync(notificationList);
        return test;
    }

    public async Task SendNotificationsAsync(UserNotification[] userNotifications)
    {
        foreach (var userNotification in userNotifications)
        {
            if (userNotification.Notification.Data is MessageNotificationData data)
            {
                var user = await _userManager.GetUserByIdAsync(userNotification.UserId);

                _emailSender.Send(
                    to: "[email protected]",
                    subject: "You have a new notification!",
                    body: data.Message,
                    isBodyHtml: true
                );
            }
        }
    }

    void IRealTimeNotifier.SendNotifications(UserNotification[] userNotifications)
    {
        throw new NotImplementedException();
    }
}

Я добавил ниже в функцию PreInitialize () в модуле .Application:

Configuration.Notifications.Notifiers.Add<MessageAppService>();

Обновление:

Я знаю, как избежать этого исключения, но хочу знать, достаточно ли шагов, которые я реализовал в своем коде, для получения уведомления.


Обновление 2:

Я применил код в вопросе, упомянутом aaron. У меня еще одно исключение:

WARN  2020-07-05 13:30:06,907 [9    ] fications.DefaultNotificationDistributer - System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
WARN  2020-07-05 13:30:09,049 [10   ] fications.DefaultNotificationDistributer - System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
ERROR 2020-07-05 13:30:28,176 [10   ] Mvc.ExceptionHandling.AbpExceptionFilter - Failure sending mail.
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.CreateAsync(CreateMessageDto input) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 153
   at Abp.Authorization.AuthorizationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Auditing.AuditingInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Runtime.Validation.Interception.ValidationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

person 3202User    schedule 05.07.2020    source источник
comment
Отвечает ли это на ваш вопрос? Что такое исключение NullReferenceException и как его исправить?   -  person Progman    schedule 05.07.2020
comment
@Progman, ни один человек, это не связано с исключением, я хочу знать Beyond exception   -  person 3202User    schedule 05.07.2020
comment
@Progman Я обновил свой вопрос, чтобы он стал более понятным   -  person 3202User    schedule 05.07.2020
comment
Отвечает ли это на ваш вопрос? Создание данных уведомления для IRealTimeNotifier   -  person aaron    schedule 05.07.2020
comment
@aaron, позволь мне проверить   -  person 3202User    schedule 05.07.2020
comment
@aaron Я так не думаю, если только уведомления публикации не связаны с несколькими уведомителями?   -  person 3202User    schedule 05.07.2020
comment
Да, как описано в связанных вопросах и ответах.   -  person aaron    schedule 05.07.2020
comment
@aaron Я внедрил ваше решение, но возникло другое исключение wxception == ›System.Net.Mail.SmtpException: Ошибка отправки почты.   -  person 3202User    schedule 05.07.2020
comment
Пожалуйста, не расширяйте рамки этого вопроса. Задайте другой вопрос.   -  person aaron    schedule 05.07.2020
comment
@aaron Я думал, это связано   -  person 3202User    schedule 05.07.2020


Ответы (1)


Вы не предоставляете нам достаточно информации. Что содержит UserNotification класс? Это ваш собственный класс или код ABP Framework?

Первая очевидная ошибка, которую я вижу, - это этот фрагмент кода:

UserNotification userNotifications = new UserNotification();
userNotifications.UserId = 10010;
//
userNotifications.Notification.TenantId = AbpSession.TenantId;
userNotifications.Notification.NotificationName = "test";

Свойство Notification не инициализировано. Я ожидал увидеть что-то вроде:

UserNotification userNotification = new UserNotification
{
   UserId = 10010,
   Notification = new Notification 
   {
     TenantId = AbpSession.TenantId,
     NotificationName = "test"
   }
};
    
person Sotiris Koukios-Panopoulos    schedule 05.07.2020
comment
UserNotification - это класс ABP и компонент Notification класса UserNotification. и я не могу инициализировать уведомление, как вы упомянули - person 3202User; 05.07.2020
comment
aspnetboilerplate.com/api-docs/html/ - person 3202User; 05.07.2020