Thursday 30 June 2011

ASP.NET MVC Mini-Profiler - Linq to SQL

This is a useful free profiler for ASP.NET MVC from the people at StackOverflow.com.

Some advice re. usage is in my previous post.

This post shows one way to use it in ASP.NET MVC with Linq to SQL.


In A DbRepository


I'm assuming a repository-based approach similar to NerdDinner.

I usually let my repository classes share a 'DataContext' - each controller typically has a main repository which creates the data context as usual, but other repositories needed in the controller actions are created using the second constructor below, and therefore use the first repository's data context.

    public class MyDbRepository : IMyRepository
    {
        public MyDataContext DataContext { get; protected set; }

        // Constructors.

        public MyDbRepository()
        {
            MiniProfiler profiler = MiniProfiler.Current;

            // Grab the SQL connection string (or could get it from web.config, for example).
            DataContext = new MyDataContext();
            string connString = DataContext.Connection.ConnectionString;

            // Setup a profiled connection.
            var conn = new SqlConnection(connString);
            var profiledConn = MvcMiniProfiler.Data.ProfiledDbConnection.Get(conn, profiler);

            // Create another data context using the profiled connection.
            DataContext = new MyDataContext(profiledConn);
        }

        public MyDbRepository(IMyRepository repos)
        {
            // Repositories can share a data context object.
            DataContext = repos.DataContext;
        }

        // Public methods.

        // +++

    }

2 comments:

  1. You don't need to (and shouldn't) check the profiler for null.

    The .Step("") extension method handles this gracefully.

    See here: http://samsaffron.com/archive/2011/06/09/+Profiling+your+website+like+a+true+Ninja

    ReplyDelete
  2. Many thanks cvallance, I'll amend the snippets.

    Jim

    ReplyDelete