hangfire-postgres / Hangfire.PostgreSql

PostgreSql Storage Provider for Hangfire
Other
358 stars 132 forks source link

How inject in hangfire postgres connection #342

Closed geinerjpc closed 7 months ago

geinerjpc commented 8 months ago

Hi,

Please help me to find a solution to inject the connection to setup hangfire from https://www.nuget.org/packages/Npgsql.DependencyInjection.

Or how setup a existing connection, because my postgres provider used managed identity, for this reason in my conn string configuration I don't have the password ( i used UsePeriodicPasswordProvider)

Thanks

azygis commented 8 months ago

Heya.

This is a blind-and-untested code which you might try, assuming you have set up the services according to Npgsql docs.

services.AddHangfire((provider, config) =>
    config.UsePostgreSqlStorage(c =>
        c.UseExistingNpgsqlConnection(provider.GetRequiredSerice<NpgsqlConnection>())));
geinerjpc commented 8 months ago

Hi, thanks Yes I am testing your solution, it works. I used service key to distinguish between different sources:

services.AddHangfire((provider, config) =>
    config.UsePostgreSqlStorage(c =>
        c.UseExistingNpgsqlConnection(provider.GetRequiredKeyService<NpgsqlConnection>(DataBaseKeyEnum.Name))));

In this way I can access my connection!

What a notice is that now keep showings a lot of warnings: "Could not place a lock on the resource 'hangfire:lock:recurring-job:ResetCheckIn' : Lock timeout" But I ran a job and works, It is normal?

azygis commented 8 months ago

Hmm, no, this is not normal. How many servers (and workers) do you have active at the same time?

I have to admit I never really used the UseExistingNpgsqlConnection directly, but rather the UseConnectionFactory. I suggest to use that to handle the connection creation instead of an explicit existing connection. Existing has different dispose mechanics which might be interfering.

The interface is pretty straight forward - inject NpgsqlDataSource and just create the connection from your data source in the method. This way the connection will be created from the source and disposed internally as it's treated as Hangfire-created connection.

geinerjpc commented 8 months ago

Thanks again!!! 1 server, 3 workers

I will try your recommendation, assuming you said: c.UseConnectionFactory(MyOwnConnFactory)

geinerjpc commented 7 months ago

Using connection factory works!!!

Thank you!!!