Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting DbContext into Repository class library

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?

like image 643
ajbeaven Avatar asked May 10 '13 08:05

ajbeaven


1 Answers

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;
    }

// ...
}
like image 78
qujck Avatar answered Oct 25 '22 22:10

qujck