繁体   English   中英

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

[英]MVC Repository Pattern - disposing multiple repositories?

在我的应用程序中,我尝试使用此ASP.NET指南来应用存储库模式,但不使用通用存储库和工作单元。

与我有关的事情正在处理。 目前,我的应用程序使用标准的Dispose()控制器方法来Dispose() DbContext

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

但是如何处置多个储存库? 例如,我有三个: bookRepositoryuserRepositorycollectionRepository 然后,我应该将它们全部放入方法中吗?

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

这是正确的方法吗? 谢谢你的回答。

您可以创建基础存储库,并由其他存储库扩展。 在基本存储库的ctor中,您可以初始化DbContext类,当要处置时,可以调用base.Dispose。 应该是这样的:

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

如果您真的不想为一个Dispose()方法创建基础存储库,则应按1对其进行处理。

暂无
暂无

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

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