【发布时间】:2021-03-07 12:06:05
【问题描述】:
我正在使用 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 和 DbContext 注册到 DI 容器并使用注入来访问它们。
-
这能回答你的问题吗? Injecting DbContext into service layer
-
@ChristianGollhardt 我做了这一切,我的问题是在控制器构造函数中传递服务
public AttributesController(AttributeService _attributeService) { attributeService = _attributeService; }没有提到
标签: c# entity-framework asp.net-core asp.net-web-api .net-5