简体   繁体   中英

Initialize dbcontext for repository in base class C#

I have alot of repository class which used DbContext variable. What is the best practices to initialize this DbContext variable?

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 . But when i use inside this function: using(var _entities = MyDbContext.Create()) all are fine? 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() :

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. 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.

I think you lack of space between the _entities variable type and the variable name.

and if your MyDbContext.Create() is returning something other than MyDbContext type, i think you should make some generic collections return value. and so you can dispose your entities without 'var' for _entities type for each method, you would use your generic type instead.

if you haven't try generic feature of c# you can try to look for a topic for generic class and generic method.

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