Linq to SQL & Castle IoC Container health check please
I've just started using both Linq to SQL and Windsor Castle IoC container for a new web application, and while everything works fine in preliminary tests, I could actually do it with a health check.
I was having problems when I tried to pull objects from the database using Linq to different parts of the application and then update them in the database. Since they were from different data contexts, I was unable to save the changes.
This way I created a single data file used throughout the application - hopefully on a per 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 a padlock to tweak it like this:
<component id="DataContextAccessor" service="DomainModel.Repositories.IDataContextAccessor, DomainModel"
type="DomainModel.Repositories.DataContextAccessor, DomainModel" lifestyle="PerWebRequest">
</component>
Then whenever I want to get into the database in a class, I just declare IDataContext datacontext
in my constructor.
- Will this (I hope) create a single data context for every web request - and not give me any race issues when there are many requests coming in at the same time?
source to share
The problem I see will be that your IDataContextAccessor interface exposes a DataContext property like this:
public interface IDataContextAccessor{
DataContext DataContext{get;}
}
The problem is that you actually tightly coupled your interface to the DataContext generated by linq, which means a mockery, and unit testing will be nearly impossible.
source to share