I'm currently developing an ASP.NET MVC application using the latest Entity Framework version and I do have some strange behaviour.
I share my context through the different repositories, so that way I can call a SaveChanges anywhere in the project, and all the changes over all my repositories are being changed.
public UnitOfWork(IDbContext context)
: base(context)
{
versioningRepository = new Repository<Versioning>(context, this);
settingRepository = new Repository<Setting>(context, this);
siteRepository = new VersionedRepository<Site, int>(context, this);
pageRepository = new VersionedRepository<Page, int>(context, this);
layoutRepository = new VersionedRepository<Layout, int>(context, this);
assemblyRepository = new VersionedRepository<Assembly, int>(context, this);
logRepository = new Repository<Log>(context, this);
}
Now, when I'm starting the application and I fire up multiple tabs requesting the same page at the same time then the following error might popup:
An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The underlying provider failed on Open.
The inner exception is:
The connection was not closed. The connection's current state is open.
The connection state might eventually change to 'Closed', 'Connecting'. As soon as the application is running and I refresh various pages, the same error does not show anymore, so can anyone tell me whe I'm having this behaviour?
Also, the following line can give me a 'NullReferenceException' and also I don't have a clue why this is happening:
return !query.Any() ? null : !query.Where(filter).Any() ? null : query.First(filter);
After a refresh, I don't get the 'NullReferenceException' neither.
Important to know that I'm using Unity to instantiate my DbContext and my UnitOfWork.
container.RegisterType<IDbContext, OxygenDataContext>();
container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager());
The IUnitOfWork interface does implement the IDisposable interface. This is implemented like:
protected virtual void Dispose(bool disposing)
{
if (disposing) { Context = null; }
}
public void Dispose()
{
Dispose(true);
}
Thanks for the help.