2

I am building a ASP.NET MVC application. I'm new to the whole Repositories/Unit Of Work patterns. I'm part way through implementing a generic repository for my EF objects.

I realise that there is an issue with ensuring that you only have a single DbContext per Http request... I'm pretty sure that I can achieve this by creating an instance using OWIN.

    /// <summary>
    /// Configures OWIN
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        // Create instance of database context
        app.CreatePerOwinContext<QuizEntitiesDbContext>(GetQuizEntitiesDbContext);
    }

    /// <summary>
    /// Returns an instance of the QuizEntitiesDbContext database context
    /// </summary>
    /// <returns></returns>
    public static QuizEntitiesDbContext GetQuizEntitiesDbContext()
    {
        return new QuizEntitiesDbContext();
    }

Now that seems fine if I want to get that instance within my controller, but really I need to be able to access this instance through my generic repository...

  • Is there a way that this can be achieved?

I'm also using Ninject dependency injector in my project and I've read that I can get an instance of objects per HTTP request for use in my application, something along the lines of this:

this.kernel.Bind(IMyDbContext).To(MyDbContext).InRequestScope();
  • Should I be using this/OWIN or both?
  • Do I need to wrap my DbContext in an interface or something?
Luke
  • 22,826
  • 31
  • 110
  • 193
  • I consider the `DbContext` as a unit of work - it *wraps a transaction*. Wrapping it in an interface makes it easier to *mock* in test code, otherwise you could `Bind` it `ToSelf` IIRC, if depending directly on `DbContext` doesn't freak you out ;) – Mathieu Guindon Sep 13 '14 at 20:57
  • I just wonder if it is wise having a separate instance of my DbContext for every repository that I use...? – Luke Sep 13 '14 at 20:58
  • 1
    Ohhhhh I see what you're saying! I can bind my QuizEntities object `ToSelf` and whenever I use it, it will get the same instance!? – Luke Sep 13 '14 at 21:01

0 Answers0