ptoniolo wrote:
Is there any place where I can add some code that can be executed after any connection to the db is opened?
I found a solution.
By implementing a ConnectionProvider, it's my code that prepares the connection objects used by NHibernate. After opening the connection I can issue sql commands.
I had many problems in setting up this code, mainly because I think that the doc is somewhat flawed: the idea of writing the class name in my
app.config with the syntax "
class,assembly" comes from some browsing of the source code and reflector; and again, the parameter is named
connection.provider_class in many pages of the doc, but that name is ignored: you have to specify
connection.provider.
Anyway, this is the skeleton of the class implemented:
Code:
public class MyConnectionProvider:
NHibernate.Connection.ConnectionProvider
{
public override IDbConnection GetConnection()
{
SqlConnection conn = new SqlConnection(this.ConnectionString);
conn.Open();
// do something here
return conn;
}
}
To force nh to use my provider, you have to put this code in the
app.config, under the
<session-factory> node:
Code:
<property name="connection.provider">
MyNamespace.MyConnectionProvider,AssemblyName
</property>
where
MyNamespace is the namespace of the class, and
AssemblyName is the name of the assembly.
In this example, my sql code executes directly after the Open(). An alternative is to attach an event handler to the StateChangeEvent, in case nh is closing and reopening the connection object.