I am trying to use Entity Framework as simple as posible. Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward. I came with this idea:
public class Entity
{
...
}
public class MyContext : DbContext
{
//Set database connection details here.
public DbSet<Entity> Entities{ get; set; }
}
Register DBContext with my implementation:
public class PersistenceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<DbContext>()
.ImplementedBy<MyContext>()
.LifestylePerWebRequest()
);
}
}
And finally I am using DBContext in controller this way:
public class HomeController : Controller
{
private DbContext db;
public HomeController(DbContext db)
{
this.db = db;
}
public ActionResult Index()
{
var entity = new Entity
{
//Set properties here.
};
db.Set<Entity>().Add(entity);
db.SaveChanges();
return View();
}
}
Is this correct approach? Could there be any memory leaks or potential DBContext lifetime management problems? Could there be any problem with too many database connections opened?
I would say that this could be correct. From my quick testing it looks like it is working even when I need to use DBContext in component which is then used in controller. So DBContext instance will be shared for everything per one request. Which is the way how it should be used, I guess.