I can see from forum and blog posts everywhere that lots of others before me have looked for a way to get the SQL statements as they're being prepared for execution. The answer typically is something along the lines of "you can't", or "you shouldn't".
Whether I should or not, that's what I wanted.
After hours of searching, investigation and failed attempts, and finally I came up with this.
Write up an interceptor:
using NHibernate;
using System.Diagnostics;
public class SqlStatementInterceptor : EmptyInterceptor
{
public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
{
Trace.WriteLine(sql.ToString());
return sql;
}
}
Of course, you don't have to Trace.WriteLine()
here, you could write it to a log file, or whatever else you need.
In your connection manager, hook up your Interceptor like so:
protected virtual void Configure(FluentConfiguration config)
{
config.ExposeConfiguration(x =>
{
x.SetInterceptor(new SqlStatementInterceptor());
});
}
It's not that complicated. From my perspective, certainly easier than trying to get all this XML pushed through Fluent to NHibernate - since Fluent abstracts the XML file away.
Keep in mind, you can only have a single Interceptor - so you may need to integrate this feature with your existing Interceptor, if you already have one. On that note, you might want to give it a broader name - e.g. MyAppInterceptor, so as not to imply a specific purpose, because you may want to add other features to it later.
Hope this is helpful to somebody else! :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…