简体   繁体   English

在基类C#中初始化存储库的dbcontext

[英]Initialize dbcontext for repository in base class C#

I have alot of repository class which used DbContext variable. 我有很多使用DbContext变量的存储库类。 What is the best practices to initialize this DbContext variable? 初始化此DbContext变量的最佳实践是什么?

I'm trying to do this in Base class with inheritance IDisposable , but my application make alot of operation in one time and i got DataReader is busy error . 我正在尝试使用继承IDisposable在基类中执行此操作,但是我的应用程序一次执行了很多操作,并且我得到了DataReader忙错误 But when i use inside this function: using(var _entities = MyDbContext.Create()) all are fine? 但是当我在此函数中using(var _entities = MyDbContext.Create())时: using(var _entities = MyDbContext.Create())都很好吗? what can be a problem and what is best way to fix it? 什么是问题,什么是最好的解决方法?

now my base class look like this: 现在我的基类如下:

public abstract class BaseRepository : IDisposable
    {
        protected readonly MyDbContext_entities;
        public BaseRepository()
        {
            _entities = MyDbContext.Create();
        }
        #region Implement IDisposable
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _entities.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }

and one of my repo used get this value with constructor: 和我的回购之一使用构造函数获取此值:

public MyRepo():base(){};

function MyDbContext.Create() : 函数MyDbContext.Create()

public static MyDbContext Create()
{
      return new MyDbContext();
}

The best practice is to inject the DbContext instance into the constructor or even better to inject a Func<DBContext> and then you can control the lifecycle of the db context on per method basis. 最佳实践是 DbContext实例注入到构造函数中,甚至更好地注入Func<DBContext> ,然后您可以根据每个方法控制db上下文的生命周期。 And you won't be needing a base class for this purpose anymore. 并且您将不再为此目的而需要基类。

This of course requires to use a DI Container, which is trivial in asp.net mvc. 当然,这需要使用DI容器,这在asp.net mvc中很简单。

I think you lack of space between the _entities variable type and the variable name. 我认为您在_entities变量类型和变量名称之间缺少空格。

and if your MyDbContext.Create() is returning something other than MyDbContext type, i think you should make some generic collections return value. 并且如果您的MyDbContext.Create()返回的不是MyDbContext类型,则我认为您应该使一些通用集合返回值。 and so you can dispose your entities without 'var' for _entities type for each method, you would use your generic type instead. 因此,您可以为每种方法的_entities类型处置不带'var'的实体,而应使用通用类型。

if you haven't try generic feature of c# you can try to look for a topic for generic class and generic method. 如果您尚未尝试使用C#的泛型功能,则可以尝试为泛型类和泛型方法查找主题。

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

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