ASP.NET CORE DI in model

本文关键字:in model DI CORE NET ASP | 更新日期: 2023-09-27 18:12:12

我想了解DI如何在新的ASP Core中工作。通过一个教程,我使它适用于控制器,但不能使它适用于模型。例如,我有一个AuthController,我注入了数据库上下文给它,但现在,我有更多的控制器,共享相同的模型,也就是Authentication,我想注入context给模型本身。下面是我写的一些代码:

来自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;
    }
    ...

我如何从模型到达数据库?

编辑:

这就是我的Authentication类的样子(构造函数可能会根据解决方案而有所不同):

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);
    }

ASP.NET CORE DI in model

你基本上是在为其他控制器创建一个可重用的服务。

从创建您想要的功能的抽象开始。

public interface IAuthenticationService {
    LoginResponseModel Login(LoginModel user);
}

的实现继承自这个接口

public class Authentication : IAuthenticationService {
    private readonly 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));
        //...other code that creates and returns an instance of LoginResponseModel
    }
}

设置好后,您需要向服务集合注册接口,以便DI框架在看到该接口时知道要注入什么。

来源:Asp。Net Core基础:依赖注入

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;"));
    // Add application services.
    services.AddTransient<IAuthenticationService, Authentication>();
}

,现在任何需要访问该服务的控制器都可以将其注入其构造函数

[Route("api/[controller]")]
public class AuthController : Controller {
    private readonly IAuthenticationService auth;
    public AuthController(IAuthenticationService auth) {
        this.auth = auth;
    }
    // POST api/login
    [HttpPost]
    [Route("login")]
    public LoginResponseModel Login([FromBody] LoginModel user) {
        return auth.Login(user);
    }
}

DI框架将处理创建和注入服务的所有繁重工作。现在您不必自己创建实例了。