I have an MVC4 web project and am using Castle Windsor as my DI container. Also, I am using Entity Framework to access a SQL database. I would like to set my Lifestyle to PerWebRequest, however, when I do so I get the following error: "The operation cannot be completed because the DbContext has been disposed".
If I use a Transient lifestyle, the error is bypassed, but it introduces a new set of problems with the Entity Framework. How can I keep the PerWebRequest lifestyle, but correct when the dispose method is called?
I am using constructor injection to pass my repository a connection string to build a new context. I also implement IDisposable. See below:
public class MySqlRepository : MyRepository, IDisposable
{
private readonly DbContext _context;
public MySqlRepository(string connectionString)
{
_context = new DbContext(connectionString);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
}
public void Dispose()
{
Dispose(true);
}
}