【问题标题】:How do I use .Net Core Dependency Injection from within a custom Class如何在自定义类中使用 .Net Core Dependency Injection
【发布时间】:2020-11-20 13:55:14
【问题描述】:

有点新手问题。我无法从 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......

 }

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

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


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

    }
 }

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

var myErrorHandler =  new ErrorHandling(`<wants me to pass context and config values here>`)

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

我错过了什么?

【问题讨论】:

  • 向服务集合注册ErrorHandling 并从构建的提供者处解决它。这将注入所需的依赖项
  • 您尝试在哪里初始化处理程序?

标签: c# asp.net-core dependency-injection


【解决方案1】:

您也可以在 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
}

如果您的页面模型中需要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;
    }

 }

这篇文章很有用:Dependency injection in ASP.NET Core

【讨论】:

  • 谢谢你的作品!唯一的问题是我从错误处理中获得的数据上下文似乎引用了与页面中其他地方使用的相同上下文,并且执行 SaveChanges() 会同时提交这两种情况,这不是所需的行为。
  • 也许数据上下文被注册为单例(在 Startup.cs 中)?
  • 谢谢。它被注册为范围,但将其更改为瞬态修复了问题。但我想这可能会在网站的其他地方出现性能问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多