简体   繁体   中英

MVC Repository Pattern - disposing multiple repositories?

In my application I'm trying to apply Repository Pattern using this ASP.NET guide , but without using Generic Repository and Unit of Work.

The thing that concerns me is disposing. At the moment, my application disposes the DbContext by using the standard Dispose() controller method:

LibraryContext db = new LibraryContext();
//
...
//
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        db.Dispose();
    }
    base.Dispose(disposing);
}

But how to dispose multiple repositories? For example, I've got three of them: bookRepository , userRepository and collectionRepository . Should I then dispose them all in the method, like:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        bookRepository.Dispose();
        userRepository.Dispose();
        collectionRepository.Dispose();
    }
    base.Dispose(disposing);
}

Is this a correct approach? Thank you for answers.

You can create base repository which is extended by the others. In the ctor of base repository you can initialize DbContext class and when you want to dispose you can call base.Dispose. It should be something like this:

public class BaseRepository<T> where T : BaseEntityWithId, new()
{
    //Represent the context of the database.
    public DbContext myContext { get; set; }

    //Represent a virtual table of the database.
    protected IDbSet<T> DbSet { get; set; }

    //Represents base constructor of the 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 you really don't want to create base repository even for one Dispose() method you should dispose them 1 by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM