Getting the Glimpse SQL tab working with Linq to SQL
I'm currently working on an ASP.NET MVC project that's using Linq to SQL for data access.
As usual, one of my first contributions was adding Glimpse (including Glimpse.MVC4 and Glimpse.Ado), initially as an easy way to confirm my suspicions of the dreaded N+1 problem.
Unfortunately, when I ran it, the SQL tab in Glimpse gave me nothing - Glimpse wasn't tapping into my data connection. The issue is Glimpse attaches itself by providing its own GlimpseDbProviderFactory which wraps the standard ones. This lets it collect information about how you're using your data connections. Our Linq to SQL implementation wasn't using this factory so I had to do the work myself.
Here's how I fixed this issue. Even if you're not using Linq to SQL, the solution is fairly generic, so you might find it'll help you as well.
First, I found the generated Data Context class. It should be in the .designer.cs file for your dbml.
[csharp highlight="10,16"]
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="MyApp")]
public partial class MyAppDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
region Extensibility Method Definitions
// snip
endregion
public MyAppDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public MyAppDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
// snip
}
[/csharp]
The highlighted lines represent two of the overloaded constructors that can be used to create a context.
Our project had been using the first one by passing in a connection string. To resolve the issue I'm having, I'm going to use the second constructor, passing in our own IDbConnection.
I need to change this:
[csharp]
var context = new MyAppDataContext(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString());
[/csharp]
to this:
[csharp]
var context = new MyAppDataContext(
new GlimpseDbConnection(
new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString())
)
);
[/csharp]
After pressing F5, everything worked beautifully and we started seeing our SQL queries come through.
All that's happening is that we're manually wrapping our connection in a GlimpseDbConnection. In short, if you have control over the creation of the IDbConnection, you can get Glimpse working with very little fuss. Of course, you'll need to include Glimpse.Ado in the project that calls this constructor.
I'm sure I don't need to tell you that you should be using Dependency Injection to inject your IDbConnection where required, making it even easier to implement!