c# - 如何在 Asp .Net 5 的控制器外使用 ApplicationDbContext
问题描述
我正在使用 Asp .Net 5 创建一个 WebApi,并且我试图将所有数据库操作放在一个单独的类中,问题是我不能通过启动一个新对象来使用 ApplicationDbContext,因为它在构造函数中需要一个参数。
我的背景:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
控制器 :
[Route("api/[controller]")]
[ApiController]
public class AttributesController : ControllerBase
{
[HttpPost]
[Route("GetAllAttributes")]
public async Task<AllAttributes> GetAllAttributes()
{
return await new Services.AttributeService().GetAll();
}
}
服务 :
public class AttributeService
{
private readonly ApplicationDbContext _db ;
public async Task<AllAttributes> GetAll()
{
try
{
var dbAttributes = await _db.Attributes.Where(attr=> (bool)attr.IsActive && !(bool)attr.IsDeleted && !(bool)attr.IsTrashed).ToListAsync();
if (dbAttributes.Count>0)
{
return new AllAttributes
{
Attributes = dbAttributes,
Message = new ResponseMessage
{
Message = "Success",
Code = 200
}
};
}
else
{
return new AllAttributes
{
Message = new ResponseMessage
{
Message = "Empty",
Code = 410
}
};
}
}
catch (Exception ex)
{
return new AllAttributes
{
Message = new ResponseMessage
{
Message = ex.Message,
Code = 500
}
};
}
}}
所以当我这样称呼它时,我得到了NullReference
异常。
解决方案
您将需要添加AttributeService
到 DI 容器。您可以在以下ConfigureServices
方法中执行此操作Startup.cs
:
services.AddScoped<AttributeService>();
然后你可以在构造函数中注入上下文AttributeService
:
public class AttributeService
{
private readonly ApplicationDbContext _db ;
public AttributeService(ApplicationDbContext db)
{
_db = db;
}
...
}
推荐阅读
- database - 归一化为 4NF?
- python - TypeError:列表索引必须是整数或切片,而不是 Windows 10 上的 str
- python-3.x - 无法插入包含 % 的记录
- arduino - PIR 运动传感器
- java - IntelliJ IDEA 不索引 GraalVM 库
- django-rest-framework - Django-rest-framework filter_queryset() 接受 3 个位置参数,但给出了 4 个
- node.js - 我的随机图像机器人尝试从主文件夹而不是指定文件夹中提取图像
- javascript - 在 Asp.Net C# 中使用 javascript 拆分多行文本框值
- javascript - 如何计算 Javascript 中图像的点击次数?
- algorithm - 具有 n 变量和范围的解决方案丢番图方程