【问题标题】:Dependency Injection asp.net core without constructor [duplicate]没有构造函数的依赖注入asp.net核心[重复]
【发布时间】:2020-10-06 05:10:20
【问题描述】:

我写了一个类似下面的类

public sealed class SomeAttribute : Attribute, IResultFilter
{ 
   private INotificationhub notificationHub;
   public void OnResultExecuting(ResultExecutingContect filterContext)
   {

     //Need to set value notificationHub by resolving dependency

    //some other logic here


   }

}

在asp.net core的ConfigureServices中

我写过

services.AddSingleton<INotificationHub, NotificationHub>();

如何解决属性类中的依赖关系。我无法进行构造函数注入。

【问题讨论】:

  • 此链接可能有用,用于演示如何注入依赖项操作过滤器。与您类似的用例。 devtrends.co.uk/blog/…

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


【解决方案1】:

以下是否适合您:

public sealed class SomeAttribute : Attribute, IResultFilter
{ 
   private INotificationhub notificationHub;
   public void OnResultExecuting(ResultExecutingContect filterContext)
   {

     //Need to set value notificationHub by resolving dependency
    notificationHub = filterContext.HttpContext.RequestServices.GetService<INotificationhub>();

        // …
    //some other logic here


   }

}

这里有优秀的文章,解释这个和其他选项:https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core

【讨论】:

  • 文章在哪里?我会试试你提供的代码,让你知道
  • 抱歉在编辑过程中错过了。
猜你喜欢
  • 1970-01-01
  • 2019-03-29
  • 2021-10-16
  • 2021-05-13
  • 1970-01-01
  • 2020-12-27
  • 2018-01-03
  • 2011-02-02
  • 1970-01-01
相关资源
最近更新 更多