3
votes

I'm facing the following problem. I have a SignalR hub like this:

public class NewsLetterHub : Hub
{
    private readonly IServicesContainer _servicesContainer;
    private readonly ILifetimeScope _hubLifetimeScope;

    public NewsLetterHub(ILifetimeScope lifetimeScope, IServicesContainer servicesContainer)
    {
        _servicesContainer = servicesContainer;
        _hubLifetimeScope = lifetimeScope.BeginLifetimeScope();

        _servicesContainer.NewsLetterService.ImportProgress += _sentNewsLetter_Progress;
    }

I register this hub in Autofac this way:

builder.RegisterHubs(Assembly.GetExecutingAssembly());

Debugging the code I see that hub constructor is called once per request but the ImportProgress event contains the previous registered handler. This brings _sentNewsLetter_Progress method to be executed multiple times.

I tryied to register the hub this way:

builder.RegisterHubs(Assembly.GetExecutingAssembly()).InstancePerLifetimeScope();

Doing this it seems to work but I don't know if this is the right solution (it becomes singleton).

I also tryied to unregister the event:

_servicesContainer.NewsLetterService.ImportProgress -= _sentNewsLetter_Progress;
_servicesContainer.NewsLetterService.ImportProgress += _sentNewsLetter_Progress; 

But it seems to do nothing.

How to prevent this behavior?

1

1 Answers

0
votes

You need to change where you're de-registering the event handler to do it in a destructor or Dispose() method. If you try to do in the constructor it will try to de-register the _sentNewsLetter_Progress handler from the instance being constructed. Since that instance isn't registered yet it will do nothing. However, if you de-register in the destructor/Dispose then it will work.