Mertez
Mertez

Reputation: 1131

Connection Closes if I define constructor for Hub

I need a constructor for my Hub to connect to the DependencyInjections. As soon as I declare a private readonly dependency variable and a constructor for my Hub -Even with no code inside it - I got ConnectionClose even before OnConnectedAsync runs.

Means OnConnectedAsync never runs!

Error: Connection disconnected with error 'Error: Server returned an error on close: Connection closed with an error.'.

private readonly Chatter _chatter;

public ChatHub(Chatter chatter)
{
    _chatter = chatter;
}

Or even

private readonly Chatter _chatter;

public ChatHub(Chatter chatter)
{
    //Empty
}

But this is OK:

private readonly Chatter _chatter;

public ChatHub()
{
    //Whatever...
}

Upvotes: 3

Views: 2043

Answers (2)

Esaith
Esaith

Reputation: 808

In my case I was trying to send in my AppSettings class. In my Startup.cs, I already had my appsettings.json class, AppSettingOptions, setup for injection for services.

services.Configure<AppSettingOptions>(Configuration.GetSection(AppSettingOptions.SettingsName));

Yet I had forgotten to use the IOptions data type as a parameter instead of the AppSettingOptions data type.

public ClassA(IOptions<AppSettingOptions> appSettingOptions)

For additional debugging if this does not solve you issue, if you set the parameter to a default value of null you should be able to at least step into the constructor on the server side instead of finding the error on the client side.

public ClassA(IOptions<AppSettingOptions> settingOptions = null)

Upvotes: 0

Nkosi
Nkosi

Reputation: 247203

You need to register your dependency so that it can be injected into the Hub.

services.AddTransient<Chatter>();

Chances are that the DI container does not know about the dependency in order to inject it, which causes the error.

Upvotes: 2

Related Questions