Sql – Linq to SQL & Castle IoC Container sanity check please

asp.netcastle-windsorinversion-of-controllinq-to-sql

I've just started using both Linq to SQL and Windsor Castle IoC container for a new web app and, although things seem to be working OK in preliminary tests, I could really do with a sanity check on it.

I was running into problems when I tried to pull objects out of the database using Linq in different parts of the app and then updating them in the database. As they were from different data contexts I couldn't save the changes.

So I have made a single datacontext used across the application – hopefully on a per web request basis. Is this a reasonable way to fix the problem?

It looks like this:

public class DataContextAccessor : IDataContextAccessor
{
    private readonly DataContext dataContext;
    public DataContextAccessor(string connString)
    {
        dataContext = new DataContext(connString);
    }
    public DataContext DataContext { get { return dataContext; } }
}

I used Castle to instiantiate this like so:

  <component id="DataContextAccessor" service="DomainModel.Repositories.IDataContextAccessor, DomainModel"
                      type="DomainModel.Repositories.DataContextAccessor, DomainModel" lifestyle="PerWebRequest">
  </component>

Then whenever I want to get at the database in a class I am just declaring IDataContext datacontext in my the constructor.

  • Will this (as I hope) create a single data context for each web request – and not give me any race problems when many requests are coming in at the same time?

Best Answer

The problem I can see you are going to have here is if your interface IDataContextAccessor exposes the DataContext property like this:

public interface IDataContextAccessor{
  DataContext DataContext{get;}
}

The problem with this is that you have actually tightly coupled your interface to the DataContext created by linq meaning mocking and unit testing will be near on impossible.

Related Topic