c# - MVC Repository Pattern - disposing multiple repositories? -
in application i'm trying apply repository pattern using this asp.net guide, without using generic repository , unit of work.
the thing concerns me disposing. @ moment, application disposes dbcontext using standard dispose() controller method:
librarycontext db = new librarycontext(); // ... // protected override void dispose(bool disposing) { if (disposing) { db.dispose(); } base.dispose(disposing); } but how dispose multiple repositories? example, i've got 3 of them: bookrepository, userrepository , collectionrepository. should dispose them in method, like:
protected override void dispose(bool disposing) { if (disposing) { bookrepository.dispose(); userrepository.dispose(); collectionrepository.dispose(); } base.dispose(disposing); } is correct approach? thank answers.
you can create base repository extended others. in ctor of base repository can initialize dbcontext class , when want dispose can call base.dispose. should this:
public class baserepository<t> t : baseentitywithid, new() { //represent context of database. public dbcontext mycontext { get; set; } //represent virtual table of database. protected idbset<t> dbset { get; set; } //represents base constructor of base repository. public baserepository() { this.mycontext = new context(); this.dbset = this.context.set<t>(); } public iobjectcontextadapter getobjectcontextadapter() { return (iobjectcontextadapter)this.context; } public virtual void dispose() { if (this.context != null) { this.context.dispose(); } } } if don't want create base repository 1 dispose() method should dispose them 1 1.