如何在 Asp .Net 5 中的控制器外部使用 ApplicationDbContext
How to use ApplicationDbContext outside the controller in Asp .Net 5
我正在使用 Asp .Net 5 创建一个 WebApi,我试图将所有数据库操作放在一个单独的 class 中,问题是我无法通过启动一个新对象,因为它在构造函数中接受一个参数。
我的背景:
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 容器。您可以在 Startup.cs
:
的 ConfigureServices
方法中执行此操作
services.AddScoped<AttributeService>();
然后可以在AttributeService
的构造函数中注入上下文:
public class AttributeService
{
private readonly ApplicationDbContext _db ;
public AttributeService(ApplicationDbContext db)
{
_db = db;
}
...
}
我正在使用 Asp .Net 5 创建一个 WebApi,我试图将所有数据库操作放在一个单独的 class 中,问题是我无法通过启动一个新对象,因为它在构造函数中接受一个参数。
我的背景:
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 容器。您可以在 Startup.cs
:
ConfigureServices
方法中执行此操作
services.AddScoped<AttributeService>();
然后可以在AttributeService
的构造函数中注入上下文:
public class AttributeService
{
private readonly ApplicationDbContext _db ;
public AttributeService(ApplicationDbContext db)
{
_db = db;
}
...
}