Injecting DbContext into Repository class library

asp.net-mvc-4 dependency-injection entity-framework inversion-of-control unity-container

Question

The projects in my solution are set up like this:

  • App.Data
  • App.Models
  • App.Web

In App.Data, I'm using Entity Framework to access my data with a bunch of Repositories to abstract interaction with it. For obvious reasons, I would like my App.Web to reference only the App.Data project and not Entity Framework.

I'm using Constructor Injection to give my Controllers a reference to a Repository container that looks like this:

public interface IDataRepository
{
    IUserRepository User { get; set; }
    IProductRepository Product { get; set; }

    // ...
}

public class DataRepository : IDataRepository
{
    private readonly AppContext _context;

    public DataRepository(AppContext context)
    {
        _context = context;
    }

    // ...
}

DataRepository will have a AppContext object (which inherits from Entity Framework's DbContext) that all the child Repositories will use to access the database.

So finally we come to my problem: how do I use Constructor Injection on DataRepository considering it's a code library and has no entry-point? I can't bootstrap AppContext in App.Web because then I have to reference Entity Framework from that project.

Or am I just doing something stupid?

1
8
5/10/2013 8:29:51 AM

Accepted Answer

You can define a RepositoryConnection class in App.Data that acts as a wrapper to the Context and removes the need to reference EF in App.Web. If you are using an IoC Container you can control the lifetime of the RepositoryConnection class to ensure that all instances of Repository get the same Context. This is a simplified example ...

public class RepositoryConnection
{
    private readonly AppContext _context;

    public RepositoryConnection()
    {
        _context = new AppContext();
    }

    public AppContext AppContext { get { return _context; } }
}

public class DataRepository : IDataRepository
{
    private readonly AppContext _context;

    public DataRepository(RepositoryConnection connection)
    {
        _context = connection.AppContext;
    }

// ...
}
12
5/10/2013 9:08:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow