Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
IMO you should'nt depend on DbContext. DbContext is plumbing to supply your own MyContext with underlying functionality. It's not an interface to use throughout your code. – rmac Jan 7 at 12:11

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.