如何在自定义类中使用 .Net Core 依赖注入

1 c# dependency-injection asp.net-core

有点新手问题。我无法从 ASP.NET Core 3.1 中我自己的自定义类中访问依赖注入服务

我可以从控制器或剃刀页面内很好地访问服务,例如我可以获取配置和数据上下文信息:

public class DetailModel : PageModel
{
    private readonly MyDataContext  _context;
    private readonly IConfiguration _config;

    public DetailModel(MyDataContext context, IConfiguration config)
    {
        _context = context;
        _config = config;   
    }

etc......

 }
Run Code Online (Sandbox Code Playgroud)

我现在希望从不是控制器或剃刀页面的自定义类的构造函数访问这些。例如我正在使用:

public class ErrorHandling
{
    private readonly MyDataContext  _context;
    private readonly IConfiguration _config;


    public ErrorHandling(MyDataContext context, IConfiguration config)
    {
        _context = context;
        _config = config;   

    }
 }
Run Code Online (Sandbox Code Playgroud)

问题是,当我实例化我的类时,它坚持要求我将服务值传递到构造函数中:

var myErrorHandler =  new ErrorHandling(`<wants me to pass context and config values here>`)
Run Code Online (Sandbox Code Playgroud)

这违背了 DI 的全部意义。我想我在这里遗漏了一些基本的东西!

我缺少什么?

arc*_*aut 5

您也可以在 Startup.cs 中注册ErrorHandling为服务:

public void ConfigureServices(IServiceCollection services)
{
    // other stuff..
    services.AddScoped<ErrorHandling>(); // this should work as long as both 'MyDataContext' and 'IConfiguration' are also registered
}
Run Code Online (Sandbox Code Playgroud)

如果您的页面模型中需要一个实例ErrorHandling,您可以在构造函数中指定它,ASP.NET Core 将在运行时为您解析它。

这样你就不必new这样做:

public class DetailModel : PageModel
{
    private readonly MyDataContext  _context;
    private readonly IConfiguration _config;
    private readonly ErrorHandling _errorHandling;

    public DetailModel(ErrorHandling errorHandling, MyDataContext context, IConfiguration config)
    {
        _context = context;
        _config = config;   
        _errorHandling = errorHandling;
    }

 }
Run Code Online (Sandbox Code Playgroud)

本文可能有用:ASP.NET Core 中的依赖注入