I'm working on a 3-tier MVC application. The data layer contains an EF4 code-first DbContext:
public class MyDataContext : DbContext
{
// DbSet<>s...
}
There's also an interface and an implementation for DI:
public interface IContextFactory
{
MyDataContext GetContext();
}
public class ContextFactory : IContextFactory
{
readonly MyDataContext context;
public ContextFactory(MyDataContext context)
{
this.context = context;
}
public MyDataContext GetContext()
{
return this.context;
}
}
And a repository pattern:
public interface IRepository<T>
{
T Create();
void Insert(T entity);
void Delete(T entity);
...
void Save();
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity: class, new()
{
public Repository(IContextFactory factory)
{
this.context = factory.GetContext();
this.set = factory.Set<TEntity>();
}
...
}
The upper tiers access the entities by having IRepository<>
injected with castle windsor. Custom providers/modules explicitly .Resolve<>()
them as needed.
The data layer is being registered in a castle IWindsorInstaller
:
container.Register(
Component.For<MyDataContext>()
.DependsOn(new Hashtable() { {"connectionStringName", "DefaultConnection"} })
.LifestylePerWebRequest());
container.Register(
Component.For<IContextFactory>()
.ImplementedBy<ContextFactory>()
.LifestylePerWebRequest());
container.Register(
Component.For(typeof(IRepository<>))
.ImplementedBy(typeof(Repository<>))
.LifestylePerWebRequest());
I wouldn't know anything was wrong - my tests don't cover the data context - but in debug mode my data context's constructor is getting called nearly a dozen times per web request.
edit: Whilst it does not explain why Repository
and MyDataContext
aren't getting scoped to web requests, my break point inside the constructor reveals an identical call stack all dozen-or-so times that its constructed: MembershipProvider.GetUser -> new Repository(IContextFactory)
. I have no explicit calls to GetUser
- what in the world would cause FormsAuthentication to call GetUser so many times?