Pergunta

Anyone knows how to configure connection string dynamically, while keeping the other parameters in the cfg.xml file?

Follows what should be contained in the cfg.xml file:

  • dialect
  • connection driver
  • query substitutions

And what needs to be programmatically configured:

  • connection string (using per-user and per-instance basis)

This means that the connection string is built dynamically, and the other parameters shall be static in the cfg.xml file (until they're changed manually in the XML).

I was wondering whether this could do the trick?

NHibernate using single configuration file to connect to multiple dbs

Sequence

  • The application is launched
  • The application prompts the user to enter both his credentials and database instance
  • The application verifies authentication against the database and either grant or refuse access based on the database response.
Foi útil?

Solução

We can combine both. There is an example, reading the configuration first, then extending it with as many settings as needed:

ISessionFactory CreateSessionFactory(string connectionString) // from outer source
{
    // the Configuration, i.e.: native, NHibernate one
    var configuration = new NHibernate.Cfg.Configuration();

    var configFile = ... // a path to configuration ;

    // read that configuration file    
    var document = XDocument.Load(configFile);

    // pass it to the Configuration 
    using (var reader = document.CreateReader())
    {
        configuration.Configure(reader);
    }

    // so, the config file is applied, 
    // no its our dynamic turn
    configuration.SetProperty("connection.connection_string", connectionString);
    configuration.SetProperty(....);

    // and now, we can ask for configuration to produce the factory
    var factory = configuration.BuildSessionFactory();

    return factory;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top