没有构造函数的依赖注入asp.net核心

时间:2020-10-06 05:10:20

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

我写了一个像下面的课

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核心的ConfigureServices中

我写了

services.AddSingleton<INotificationHub, NotificationHub>();

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

1 个答案:

答案 0 :(得分:2)

为您完成以下工作:

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

相关问题