我只使用存储库模式。 BaseRepository是所有存储库类的基本抽象类,它创建和配置dbContext。似乎一切正常,但在代码分析期间,Virtual Studio会给我一个警告:
CA2214不要调用可覆盖的方法 构造函数' BaseRepository.BaseRepository(string, ApplicationDbContext)'包含一个调用链,导致调用 由类定义的虚方法。
我在构造函数中创建ApplicationDbContext的新对象(此类直接从IdentityDbContext继承)。 是不好的做法?我不想在任何扩展类中重写Dispose(但它必须是虚拟的,因为VS说我没有错误地实现IDisposable)。 如果错误的话我怎么能以更好的方式做到这一点,在构造函数中创建dbcontext的所有利润都给出了(没有默认上下文的简单测试,不需要在所有repo方法中创建上下文等)?
这是我的代码:
public abstract class BaseRepository : IDisposable
{
protected ApplicationDbContext context { get; private set; }
protected String userName;
protected BaseRepository(string userName, ApplicationDbContext context)
{
this.context = context;
if(userName != null)
this.userName = userName;
else{
Dispose(); //that is unnecessary and stupid piece of code
throw new Exception();
}
}
protected BaseRepository(string userName) : this(userName, new ApplicationDbContext()) { }
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
context.Dispose();
}
}
}
抱歉我的错,我在构造函数中有可以调用Dispose()函数(我试过有简单的代码,我不在这里写)。再次抱歉,我保证永远不会再删除我的代码"简单"以那种愚蠢的方式。谢谢大家的帮助和时间。
答案 0 :(得分:0)
您无法调用受保护的构造函数,该构造函数从类本身获取参数。受保护的方法只能从类派生类中调用。