【发布时间】:2019-07-11 12:31:27
【问题描述】:
我有 .net core 2.1 项目。我的存储库类如下所示。但由于MyDbContext 构造函数有参数,我收到如下错误。当我删除 JwtHelper 参数时,它运行良好。 但是,我需要在 MyDbContext.cs 中添加 JwtHelper 以进行日志审核。我怎样才能做到这一点?
“MyDbContext”必须是具有公共无参数构造函数的非抽象类型,才能将其用作泛型类型或方法“UnitOfWork”中的参数“TContext”
UnitOfWork.cs
public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DbContext, new()
{
protected readonly DbContext DataContext;
public UnitOfWork()
{
DataContext = new TContext();
}
public virtual async Task<int> CompleteAsync()
{
return await DataContext.SaveChangesAsync();
}
public void Dispose()
{
DataContext?.Dispose();
}
}
IUnitOfWork.cs
public interface IUnitOfWork<U> where U : DbContext
{
Task<int> CompleteAsync();
}
MyRepos.cs
public class MyRepos : UnitOfWork<MyDbContext>, IMyRepos
{
private IUserRepository userRepo;
public IUserRepository UserRepo { get { return userRepo ?? (userRepo = new UserRepository(DataContext)); } }
}
IMyRepos.cs
public interface IMyRepos : IUnitOfWork<MyDbContext>
{
IUserRepository UserRepo { get; }
}
MyDbContext.cs
public class MyDbContext : DbContext
{
private readonly IJwtHelper jwtHelper;
public MyDbContext(IJwtHelper jwtHelper) : base()
{
this.jwtHelper= jwtHelper;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var userId=jwtHelper.GetUserId();
SaveAudits(userId,base.ChangeTracker);
return (await base.SaveChangesAsync(true, cancellationToken));
}
}
UserRepository.cs
public class UserRepository : Repository<User>, IUserRepository
{
private readonly MyDbContext_context;
public UserRepository(DbContext context) : base(context)
{
_context = _context ?? (MyDbContext)context;
}
}
IUserRepository.cs
public interface IUserRepository : IRepository<User>
{ }
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IJwtHelper, JwtHelper>();
services.AddScoped<DbContext, MyDbContext>();
services.AddTransient<IMyRepos, MyRepos>();
}
【问题讨论】:
-
您是否需要
UnitOfWork<TContext>类中TContext参数的new()约束?如果是这样,您将需要一个无参数构造。顺便说一句,您可以拥有多个构造函数。 -
所以,
UnitOfWork想要运行DataContext = new TContext();。从哪里获取IJwtHelper(如果允许对其进行参数化)? -
感谢@CoolBots。我现在通过添加我的 UnitOfWork 类的内容来编辑我的问题。你能检查我的 UnitOfWork 课程吗?
DataContext = new TContext();有什么不同的方式吗? 如果可能,那么我删除new()约束。 -
如果您可以将参数传递给您的
UnitOfWork构造函数,只需将已构造的TContext传递给它并消除new()约束即可。 -
是的,但是如果您仍然希望
UnitOfWork创建实例,传递帮助程序,您需要给它一个Func<IJwtHelper, TContext>帮助程序,其中可以包含您指定的特定new代码不能在泛型内部。
标签: c# entity-framework asp.net-core-2.1