c# - 带有 GenericRepository 错误的依赖注入 - 没有为此 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 呢?
当我尝试像这样注册上下文时:
// 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
推荐阅读
- git - 破碎的 Git 树
- templates - 与传递的实体一起扩展 base.twig
- php - 在每个 div 中回显消息或在 php 中单独的 css div
- java - activity_registo_login.xml:19:错误:“43”与属性 layout_height (attr) 维度不兼容|枚举
- slack - Slack - 发送前确认
- dart - Dart BLoC 与 Stream 需要在两个接收器中的任何一个更新时更新
- javascript - 稍后捕获 Promise 拒绝
- uipath - 我有两行,我正在尝试删除第二行
- java - SQLException: ORA-01652: 无法在表空间 TEMPORAL 中将临时段扩展 128
- ms-access - 无法压缩访问 MDB