简体   繁体   English

MVC存储库模式-部署多个存储库?

[英]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. 在我的应用程序中,我尝试使用此ASP.NET指南来应用存储库模式,但不使用通用存储库和工作单元。

The thing that concerns me is disposing. 与我有关的事情正在处理。 At the moment, my application disposes the DbContext by using the standard Dispose() controller method: 目前,我的应用程序使用标准的Dispose()控制器方法来Dispose() DbContext

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 . 例如,我有三个: bookRepositoryuserRepositorycollectionRepository 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. 在基本存储库的ctor中,您可以初始化DbContext类,当要处置时,可以调用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. 如果您真的不想为一个Dispose()方法创建基础存储库,则应按1对其进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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