繁体   English   中英

带有 GenericRepository 错误的依赖注入 - 没有为此 DbContext NET.Core 3.1 配置数据库提供程序

[英]Dependency Injection with GenericRepository error - No database provider has been configured for this DbContext NET.Core 3.1

使用 GenericRepository 启动我的应用程序时出现错误。 (没有为此 DbContext 配置数据库提供程序。)。

我如何修改我的 GenericRepository 才能解决这个问题? 这是我的代码:

IRepository.cs

public interface IRepository<TEntity> where TEntity : class
{

    /*void Delete(TEntity entityToDelete);
    void Delete(object id);*/
    IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "");

    TEntity GetById(object id);
    Task<TEntity> GetByIdAsync(object id);

    /*IEnumerable<TEntity> GetWithRawSql(string query,
        params object[] parameters);*/
    void Insert(TEntity entity);
    TEntity Update(long id, Action<TEntity> action);
    }

通用存储库.cs

public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        internal Context context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(Context context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>(); // here's the error (No database provider...)
        }

        public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetById(object id)
        {
            return dbSet.Find(id);
        }

        public async Task<TEntity> GetByIdAsync(object id)
        {
            return await dbSet.FindAsync(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
            context.SaveChanges();
        }

        public virtual void Remove(object id)
        {
            TEntity entityToDelete = GetById(id);
            Remove(entityToDelete);
        }

        public void Remove(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entity)
        {
            dbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
        }

        public TEntity Update(long key, Action<TEntity> action)
        {
            var model = dbSet.Find(key);
            if(model != null)
            {
                Update(model);
                action(model);
            }
            return model;
        }

    }

依赖解析器.cs

public class DependencyResolver
    {
        public IServiceProvider ServiceProvider { get; }

        public DependencyResolver()
        {
            // Set up Dependency Injection
            IServiceCollection services = new ServiceCollection();

            ConfigureServices(services);
            ServiceProvider = services.BuildServiceProvider();
        }

        private void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient(typeof(IRepository<>), typeof(GenericRepository<>));

            // Register DbContext class
            services.AddTransient(provider =>
            {
                var configService = provider.GetService<IConfigurationService>();
                //var connectionString = configService.GetConfiguration().GetConnectionString("uRP");
                var optionsBuilder = new DbContextOptionsBuilder<Context>();
                optionsBuilder.UseMySql("server=localhost;database=uRP;user=root;password=;", builder => builder.MigrationsAssembly(typeof(Context).GetTypeInfo().Assembly.GetName().Name));

                return new Context(optionsBuilder.Options);
            });

            services.AddScoped<IAccountService, AccountService>();
            services.AddScoped<IUnitOfWork, UnitOfWork.UnitOfWork>();

        }
    }

上下文.cs

public class Context : DbContext
{
public Context(DbContextOptions<Context> options) : base(options)
{

}

public Context()
{

}



public DbSet<AccountModel> Players { get; set; }
public DbSet<CharacterModel> Characters { get; set; }
}

和 ContextTimeDesignFactory.cs

    class ContextDesignTimeFactory : IDesignTimeDbContextFactory<Context>
{
    public Context CreateDbContext(string[] args)
    {
        var resolver = new DependencyResolver();
        return resolver.ServiceProvider.GetService(typeof(Context)) as Context;
    }
}

都有不错的。 我有一个 IAccountRepository 和 ICharacterRepository,它运行良好。 如何在 GenericRepository.cs 中设置 DbContextOptions?

注册上下文似乎是一个错误。

您有 ContextDesignTimeFactory 中使用的 DependencyResolver。 但是如何在应用程序中注册 Context 呢?

当我尝试像这样注册 Context 时:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddTransient(provider =>
    {
        var optionsBuilder = new DbContextOptionsBuilder<Context>();
        optionsBuilder.UseMySql(
            "server=localhost;database=uRP;user=root;password=;",
            builder => builder.MigrationsAssembly(typeof(Context).GetTypeInfo().Assembly.GetName().Name));

        return new Context(optionsBuilder.Options);
    });

    services.AddTransient(typeof(IRepository<>), typeof(GenericRepository<>));
}

解析 GenericRepository 没有错误。

但是当我将注册更改为

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddTransient<Context>();

    services.AddTransient(typeof(IRepository<>), typeof(GenericRepository<>));
}

我在同一个地方有完全相同的例外。

希望有帮助

PS 对于 DbContext 注册有一个特定的方法AddDbContext

暂无
暂无

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

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