Ends in:
3 DAYS
6 HRS
23 MIN
48 SEC
Ends in:
3 D
6 H
23 M
48 S
Open Closed

Not able to add event listener in constructor #8298


User avatar
0
Bryan-EDV created

Error messages

[10:59:10 INF] Executing endpoint '/signalr-hubs/messaging'
[10:59:11 ERR] Error when dispatching 'OnConnectedAsync' on hub.
Autofac.Core.DependencyResolutionException: An exception was thrown while activating Castle.Proxies.MessagingHubProxy -> Eduverse.WebRtc.CommunicationService.
 ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(Microsoft.Extensions.Logging.ILogger`1[Eduverse.WebRtc.CommunicationService], Eduverse.WebRtc.IWebRtcDispatcher, Eduverse.SpeechToText.ISpeechToText, Microsoft.Extensions.Options.IOptions`1[Eduverse.WebRtc.WebRtcOptions], Eduverse.DialogueManagers.IDialogueManagersAppService)' on type 'CommunicationService'.
 ---> System.InvalidOperationException: Method may only be called on a Type for which Type.IsGenericParameter is true.
   at System.RuntimeType.get_DeclaringMethod()
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
   --- End of inner exception stack trace ---
   at Autofac.Core.Activators.Reflection.BoundConstructor.Instantiate()
   at Autofac.Core.Activators.Reflection.ReflectionActivator.<>c__DisplayClass14_0.<UseSingleConstructorActivation>b__0(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Builder.RegistrationBuilder`3.&lt;&gt;c__DisplayClass41_0.&lt;PropertiesAutowired&gt;b__0(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, 
Action`1 next)
   --- End of inner exception stack trace ---
   at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, 
Action`1 next)
   at Autofac.Builder.RegistrationBuilder`3.&lt;&gt;c__DisplayClass35_0.&lt;OnPreparing&gt;b__0(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Middleware.CoreEventMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Lifetime.LifetimeScope.CreateSharedInstance(Guid id, Func`1 creator)
   at Autofac.Core.Lifetime.LifetimeScope.CreateSharedInstance(Guid primaryId, Nullable`1 qualifyingId, Func`1 creator)
   at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action`1 next) 
   at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest& request)
   at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest& request)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubActivator`1.Create()
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection)
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection)
   at Microsoft.AspNetCore.SignalR.HubConnectionHandler`1.RunHubAsync(HubConnectionContext connection)
[10:59:11 INF] Executed endpoint '/signalr-hubs/messaging'

Code snippets: Communication Service injected into MessagingHub

[Authorize(Roles = DefaultRoleConsts.Learner)]
[DisableConventionalRegistration]
public class MessagingHub : AbpHub
{
    private readonly ILogger<MessagingHub> _logger;
    private readonly ICommunicationService _communicationService;

    public MessagingHub(
        ILogger<MessagingHub> logger,
        ICommunicationService communicationService,
        IUnitOfWorkManager unitOfWorkManager
    )
    {
        _logger = logger;
        _communicationService = communicationService;
    }

CommunicationService snippet

public class CommunicationService : ICommunicationService
{
    private readonly ILogger<CommunicationService> _logger;
    private readonly ISpeechToText _stt;
    private readonly IWebRtcDispatcher _dispatcher;
    private readonly IDialogueManagersAppService _dialogueManagersAppService;

    public CommunicationService(ILogger<CommunicationService> logger,
        IWebRtcDispatcher dispatcher,
        ISpeechToText stt,
        IOptions<WebRtcOptions> options,
        IDialogueManagersAppService dialogueManagersAppService)
    {
        _logger = logger;
        _dispatcher = dispatcher;
        _stt = stt;
        _dialogueManagersAppService = dialogueManagersAppService;


        // SetupHandler();
        _dialogueManagersAppService.OnChatResponseChunkReceived += (sender, evt) => {
            _dispatcher.GetWebRtcPeerConnectionFromConversationId(evt.ConversationId, out var peerConnection);
            if(peerConnection == null){
                _logger.LogError("PeerConnection not found for conversationId: {conversationId}", evt.ConversationId);
                return;
            }

            var message = new { type = "chatChunk", data = evt.Text };
            var jsonString = JsonSerializer.Serialize(message);
            peerConnection.SendData(jsonString);
        };

DialogueManager Snippet

[RemoteService(IsEnabled = false)]
    public class DialogueManagersAppService : EduverseAppService, IDialogueManagersAppService
    {
        protected IConversationLogRepository _conversationLogRepository;
        protected ConversationLogManager _conversationLogManager;
        protected IConversationRepository _conversationRepository;
        protected ConversationManager _conversationManager;
        protected IFeedbackLogRepository _feedbackLogRepository;
        protected FeedbackLogManager _feedbackLogManager;
        protected IScenarioRepository _scenarioRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        protected ILlmService _llmService;
        public event EventHandler<ChatResponseChunkEventArgs>? OnChatResponseChunkReceived;
        public event EventHandler<ChatResponseEndedEventArgs>? OnChatResponseEnded;

17 Answer(s)
  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello ,

    Please check this link https://abp.io/support/questions/7463/Event-mechanism

    Thank you.

  • User Avatar
    0
    Bryan-EDV created

    Hi,

    I am aware of the local event bus. However would prefer to use the conventional EventHandler<TEventArgs> delegate to set up events as some other parts of our application has used those and we would like to ensure code consistency.

    Are you able to provide any insights as to why the dependency injection was failing?

    Thanks

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    This is a dependency injection issue,

    first

    public class CommunicationService : ICommunicationService, ITransientDependency
    

    And reduce the services injected to trace the source of the problem

  • User Avatar
    0
    Bryan-EDV created

    Hi ShiWei,

    I've noticed a similar error message pop up whenever I try to call this method in ICommunicationService

        Task HandleMessage(string connectionId, string message, System.Func&lt;string, string, Task> signalCallback)
    

    I've made CommunicationService inherit MyApplicationAppService and the moment this method is called, it throws an error with the same message as shown above

    In MessagingHub the error is thrown when the code at line 50 is called

    the signalCallback passed into HandleMessage is being defined in MessagingHub:

    public async Task SendMessage(string connectionId, string message)
        {
            _logger.LogInformation(">>> Sending WebRTC message to {connectionId}: {message}", connectionId, message);
            await Clients.Client(connectionId).SendAsync("ReceiveWebRtcMessage", message);
        }
    

    Do you have any insights to the error message and possible resolution for it? I have some suspicion that it is something to do with Func<string, string, Task> callback function passed as a parameter

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    could you provider a test project? I will check it. my email is shiwei.liang@volosoft.com

  • User Avatar
    0
    Bryan-EDV created

    Thank you ShiWei,

    I've sent the file.

    Once application launched, go to https://localhost:44349/htmlpage.html then send a message. You will see this in your dev tools

    Then, you will see the BE error console as raised above (snippet):

    Method may only be called on a Type for which Type.IsGenericParameter is true. etc...
    

    To resolve the error, check out my commented code in MessagingHub.cs. Swap out the method overload. However this would not allow us to pass a callback function.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    yes, the Interceptor can't handle this.

    you can try:

    public class MessageHandlingService : IMessageHandlingService, ITransientDependency
    {
        
        
        public virtual async Task HandleMessage(string connectionId, string message, Func<string, string, Task> sendMessageCallback)
        {
            Console.WriteLine(connectionId);
            Console.WriteLine(message);
            await sendMessageCallback(connectionId, message);
        }
    
        public virtual Task HandleMessage(string connectionId, string message)
        {
            Console.WriteLine(connectionId);
            Console.WriteLine(message);
            return Task.CompletedTask;
        }
    }
    
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Or

    Move MessagingHub to Application project.

    public class MessageHandlingService : AbpSolution7AppService, IMessageHandlingService
    {
        private readonly IHubContext<MessagingHub> _messagingHub;
    
        public MessageHandlingService(IHubContext<MessagingHub> messagingHub)
        {
            _messagingHub = messagingHub;
        }
    
        public virtual async Task HandleMessage(string connectionId, string message)
        {
            Console.WriteLine(connectionId);
            Console.WriteLine(message);
            await _messagingHub.Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
        }
    }
    
  • User Avatar
    0
    Bryan-EDV created

    Thank you Shi Wei,

    When i don't inherit the MyApplicationAppService in my application service, it just means that:

    1. I need to manually register for dependency injection using ITransientDependency/ IScopedDependency / ISingletonDependency
    2. No access to ABP defined properties such as CurrentUser / CurrentTenant
    3. Any other critical changes to consider?

    Is there any impact on the UOW scope? All along I've not inherited MyApplicationAppService and I realized that for my DB transactions to complete, I keep needing to add

    using(var uow = _unitOfWorkManager.Begin(requiresNew: true)){ 
    ...
    

    Does that relate to inheriting MyApplicationAppService? Or is that because everything is happening in a single UOW for the websocket connection?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Is there any impact on the UOW scope? All along I've not inherited MyApplicationAppService and I realized that for my DB transactions to complete, I keep needing to add Does that relate to inheriting MyApplicationAppService?

    yes, there is no Interceptor(uow, audit) any more.

  • User Avatar
    0
    Bryan-EDV created

    Or

    Move MessagingHub to Application project.

    public class MessageHandlingService : AbpSolution7AppService, IMessageHandlingService 
    { 
        private readonly IHubContext<MessagingHub> _messagingHub; 
     
        public MessageHandlingService(IHubContext<MessagingHub> messagingHub) 
        { 
            _messagingHub = messagingHub; 
        } 
     
        public virtual async Task HandleMessage(string connectionId, string message) 
        { 
            Console.WriteLine(connectionId); 
            Console.WriteLine(message); 
            await _messagingHub.Clients.Client(connectionId).SendAsync("ReceiveMessage", message); 
        } 
    } 
    

    Thank you Shi Wei,

    In that case I will attempt this method, so as to maintain any auditing / uow capabilities.

    Just to clarify the application structure is like this MessageHub --has-a--> Service1 (does not inherit xxxAppService) --has-a--> Service2 (inherits xxxAppService)

    would the method calls in Service 2 have an interceptor (uow, auditing) capabiilities? Thank you

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    would the method calls in Service 2 have an interceptor (uow, auditing) capabiilities? Thank you

    yes, it will.

  • User Avatar
    0
    Bryan-EDV created

    That's strange, because currently any of my DB operations will not update the DB until the application is shut down. I've tried using the [UnitOfWork] attribute, and also the autoSave = true in the .InsertAsync method

    Any suggestions besides using the UnitOfWorkManager?

  • User Avatar
    0
    Bryan-EDV created

    FYI I found this: https://github.com/abpframework/abp/issues/18793

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    you can try this https://abp.io/support/questions/8298/Not-able-to-add-event-listener-in-constructor#answer-3a167923-23f7-3305-416c-1bac7dd035ed

  • User Avatar
    0
    Bryan-EDV created

    Thank you, I think we can close off this ticket then.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    okay : )

Made with ❤️ on ABP v9.1.0-preview. Updated on December 02, 2024, 12:35