我想了解DI如何在新的ASP Core中工作。通过教程,我使它适用于控制器,但无法使其适用于模型。例如,我有一个AuthController,并且我向它注入了数据库上下文,但是现在,由于我有更多的控制器,共享相同的模型,即Authentication
,我希望将上下文注入模型本身。下面是一些代码片段我:模型中的ASP.NET CORE DI
从Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<GameContext>(options => options.UseSqlServer(@"Data Source=DESKTOP-USER\SQLEXPRESS;Initial Catalog=Db7;Integrated Security=True;Connect Timeout=30;"));
}
,这里是我如何使用它的控制器:
[Route("api/[controller]")]
public class AuthController : Controller
{
public GameContext db;
public AuthController(GameContext context)
{
db = context;
}
[HttpPost]
[Route("login")]
public LoginResponseModel Login([FromBody] LoginModel user) //public Models.VM.LoginModel Login([FromBody] Models.VM.LoginModel user)
{
//query user
var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password);
如果我删除的情况下部分从控制器,和将它移动到模型中,由于构造函数需要参数(我们将自动注入该参数?),我将无法再将其重新安装,
public class Authentication
{
public GameContext db;
public Authentication(GameContext context)
{
db = context;
}
...
如何从模型到达数据库?
编辑:
这是我的验证类会是什么样子(构造函数可基于该解决方案会有所不同):
public class Authentication
{
public GameContext db;
public Authentication(GameContext context)
{
db = context;
}
public LoginResponseModel Login(LoginModel user)
{
//query user
var detectedUser = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == HelperClass.Md5(user.Password));
这里就是我想用此模型控制器:
[Route("api/[controller]")]
public class AuthController : Controller
{
public AuthController(GameContext context)
{
}
// POST api/login
[HttpPost]
[Route("login")]
public LoginResponseModel Login([FromBody] LoginModel user) //public Models.VM.LoginModel Login([FromBody] Models.VM.LoginModel user)
{
Authentication auth = new Authentication(); //throws error since no parameter passed
return auth.Login(user);
}
你打算如何实例化模型?试图了解你打算如何使用模型。你的解释不清楚。你是否用模型替换了控制器构造函数中的上下文? – Nkosi
添加了更多的信息 –
好吧,我想我现在明白了。起草答案 – Nkosi