Search code examples
c#postgresqlasp.net-corenpgsql

Npgsql Password Provider only changes the password, not the entire connection string


In NpgsqlDatasourceBuilder, .UsePasswordProvider and .UsePeriodicPasswordProvider only change the password, not the connection string.

Is this the normal behavior of both ?

If so, what is the purpose of the NpgsqlConnectionStringBuilder parameter of the provider function ?

Here what I tried :

var ds = new NpgsqldataSourceBuilder(null)
   .UsePeriodicPasswordProvider((b,c)=>{b.Host="host"; b.Database="db"; etc})

Error:host can't be null

var ds = new NpgsqldataSourceBuilder("")
    .UsePeriodicPasswordProvider((b,c)=>{b.Host="host"; b.Database="db"; etc})

Error:host can't be null


Solution

  • Yes, you must first create the connection string, and then you can supply the password using one of these functions.

    The doc says Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>? passwordProvider is a "A callback which returns the password to be sent to PostgreSQL."

    Also, the doc of NpgsqlConnectionStringBuilder says "Provides a simple way to create and manage the contents of connection strings".

    One can therefore get parameters of the connection, such as the host or user, before attempting to get a new password.

    Tests are always a good source of information to help understand how to use a functionality.

    On a side note, it makes sense that solely the password is to be updated by a PeriodicPasswordProvider. If it was changing anything else it would have been named differently.