首页 > 解决方案 > 如何在 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异常。

标签: c#entity-frameworkasp.net-coreasp.net-web-api.net-5

解决方案


您将需要添加AttributeService到 DI 容器。您可以在以下ConfigureServices方法中执行此操作Startup.cs

services.AddScoped<AttributeService>();

然后你可以在构造函数中注入上下文AttributeService

public class AttributeService
{
    private readonly ApplicationDbContext _db ;

    public AttributeService(ApplicationDbContext db) 
    {
        _db = db;
    }
    ...
 }

推荐阅读