entity framework - Injecting DbContext into Repository class library -
the projects in solution set this:
- app.data
- app.models
- app.web
in app.data, i'm using entity framework access data bunch of repositories abstract interaction it. obvious reasons, app.web reference app.data project , not entity framework.
i'm using constructor injection give controllers reference repository container looks 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 have appcontext object (which inherits entity framework's dbcontext) child repositories use access database.
so come problem: how use constructor injection on datarepository considering it's code library , has no entry-point? can't bootstrap appcontext in app.web because have reference entity framework project.
or doing stupid?
you can define repositoryconnection class in app.data acts wrapper context , removes need reference ef in app.web. if using ioc container can control lifetime of repositoryconnection class ensure instances of repository same context. simplified example ...
public class repositoryconnection { private readonly appcontext _context; public repositoryconnection() { _context = new appcontext(); } public appcontext appcontext { { return _context; } } } public class datarepository : idatarepository { private readonly appcontext _context; public datarepository(repositoryconnection connection) { _context = connection.appcontext; } // ... }
Comments
Post a Comment