I got an ASP.NET MVC application which uses EF to handle DB. I've used DDD as the architecture and I got the Repository and Service patterns.
I'm trying to use StructureMap for DI but for some reason my DB got disposed after the first request.
Edit: The error I'm error I'm getting is
The operation cannot be completed because the DbContext has been disposed.
It seems that I'm getting it in the repository, for instance in:
public class AccountRepository : Repository<Account>, IAccountRepository
{
public AccountRepository(MyDbContext context) : base(context) { }
public Account FindAccountByEmailAddress(string emailAddress, bool loadRelatedRoles = false)
{
IQueryable<Account> query = (from a in Entity
where a.LoweredEmailAddress == emailAddress.ToLower()
select a);
if (loadRelatedRoles)
{
return query.Include(a => a.Roles).FirstOrDefault();
}
return query.FirstOrDefault();
}
}
In the Application_BeginRequest I'm registering the DB using
ObjectFactory.Configure(x =>
{
x.For(typeof(MyDbContext))
.HttpContextScoped();
});
In order to reserve it as one instance per request.
In the Application_EndRequest I'm releasing the request using:
protected void Application_EndRequest(object sender, EventArgs e)
{
StructureMap.ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
Am I missing something? or my approch is OK and there's maybe a problem with my Repository implementation that making it happen.