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

问题描述 投票:0回答: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);
    }

Generic Repository.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;
        }

    }

DependencyResolver.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>();

        }
    }

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

c# dependencies code-injection irepository
1个回答
1
投票

似乎是上下文注册的错误。

您具有在ContextDesignTimeFactory中使用的DependencyResolver。但是如何在应用程序中注册上下文?

当我尝试这样注册上下文时:

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

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

希望有帮助

P.S。对于DbContext,注册具有特定的方法AddDbContext

© www.soinside.com 2019 - 2024. All rights reserved.