目录
C#程序调试错误集
1.依赖注入错误System.InvalidOperationException: Unable to resolve service for type 'xxx' while attempting to activate 'xxx'.
1.1 出错现象
System.InvalidOperationException: Unable to resolve service for type 'IBMS.Infrastruct.UoW.UnitOfWork' while attempting to activate 'IBMS.WEBAPI.Controllers.ValueController'.
出错图片如下:
1.1.1原因是net core在调用ValueController的时候,发现UnitOfWork没有进行依赖注入。
1.2 出错现象
System.InvalidOperationException: Unable to resolve service for type 'IBMS.Infrastruct.Context.IPBoxContext' while attempting to activate 'IBMS.Infrastruct.UoW.UnitOfWork'.
出错图片如下:
1.2.1 原因是net core在调用UnitOfWork的时候,发现IPBoxContext没有进行依赖注入。
1.3 解决方法
在startup.cs中的ConfigureServices方法中进行依赖注入
services.AddDbContext<IIPBoxContext, IPBoxContext>(options =>
options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));
services.AddScoped<IIPBoxRepository, IPBoxRepository>();
services.AddScoped(typeof(UnitOfWork));//注入工作单元
services.AddScoped(typeof(IPBoxContext));
注意:IPBoxContext进行AddDbContext注入数据上下文之后,仍需要注入services.AddScoped(typeof(IPBoxContext))。
2. 未创建实例错误
2.1 出错现象Object reference not set to an instance of an object.
出错图片如下:
2.1.1 原因是没有创建数据库上下文对象
2.2 出错现象System.ArgumentNullException: Value cannot be null.
出错图片如下:
2.2.1 原因是没有创建数据库上下文对象
2.3 解决方法
在服务层创建一个实例的仓储,并传入其对应的数据上下文。
public class IPBoxServices : ServicesBase<IPBox>, IIPBoxServices
{
public IPBoxContext DbContext { get; set; } = null;
public IPBoxServices(IPBoxContext dbContext)
{
DbContext = dbContext;
}
#region 字段
private IPBoxRepository _IPBoxRepository = null;
#endregion
#region 操作类属性
public IPBoxRepository IPBoxRepository => _IPBoxRepository ?? (_IPBoxRepository = new IPBoxRepository(DbContext));
#endregion
}
备注:这里最好是在RepositoryBase里直接通过数据库工厂模式创建一个数据库的上下文,这样不会让仓储层泄露到应用层。当然以上方法基本没什么很大影响。
3.传入EF Core 拉姆达(lambda)表达式为空报错
3.1 出错现象
System.ArgumentNullException: Value cannot be null. at lambda_method(Closure , Object , Object[] )
出错图片如下
3.1.1 原因
获取列表数据时传入lambda表达式为空。具体如下。AlarmList = _alarmServices.GetList();
3.2解决方法
当lambda表达式为空时,直接返回列表数据。问题得到有效解决
if (predicate == null)
{
return _dbSet.ToList();
}
整个代码块如下:
public List<TEntity> GetList(Expression<Func<TEntity, bool>> predicate = null, string ordering = "", bool isNoTracking = true)
{
if (predicate == null)
{
return _dbSet.ToList();
}
var data = isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate);
if (!string.IsNullOrEmpty(ordering))
{
data = data.OrderByBatch(ordering);
}
return data.ToList();
}