Igor Bendrup
Igor Bendrup

Reputation: 2837

NHibernate: how to set connection timeout

Is there any way to globally setup time you would wait for connecting to a given database, before a connection failure in NHibernate (connection timeout)? In ADO.NET you can do it for a single connection like this:

new SqlConnection().ConnectionTimeout = 10;

I found how to setup the time you would wait for a result set, before a command execution failure here (command timeout). But, apparently, that's not what I need

Upvotes: 14

Views: 24100

Answers (3)

amcdermott
amcdermott

Reputation: 1585

You can use the connection_timeout setting in your NHibernate configuration code. See section 3.4 of the documentation for full details.

The XML configuration for this is as follows...

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
        <property name="connection.connection_string">
            Server=(local);initial catalog=theDb;Integrated Security=SSPI
        </property>
        <property name="connection_timeout">100</property>
    </session-factory>
</hibernate-configuration>

<!-- other app specific config follows -->

I'm using Fluent NHibernate so my configuration code is as follows...

FluentConfiguration configuration = Fluently.Configure()
                         .Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnectionString))
                         .ExposeConfiguration(cfg => cfg
                            .SetProperty("connection_timeout", "100")
                         .Mappings(m =>
                         {
                             var cfg = CreateAutomappings();
                             m.AutoMappings.Add(cfg);
                         });

Upvotes: 20

Roger
Roger

Reputation: 1950

You can set it on the connection string, "Connection Timeout=x".

Upvotes: 12

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

With NHibernate you can provide the connection yourself:

sessionFactory.openSession(myConnection);

I wouldn't recommend it, because it's easier when sessions are managed by NHibernate.

You can still write your own connection provider, which sets whatever you want on the created connections.

Upvotes: 1

Related Questions