0

I have written a class like below

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


   }

}

in ConfigureServices of asp.net core

I have written

services.AddSingleton<INotificationHub, NotificationHub>();

How can I resolve the dependecy in the attribute class. I cannot do a constructor injection.

user3048027
  • 387
  • 1
  • 5
  • 24
  • This link may be of use, to demonstrate how to inject dependencies action filters. A similar use case as yours. https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core – Tejas Parnerkar Oct 06 '20 at 05:38

1 Answers1

2

Does the following work for you:

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


   }

}

Excellent article here, explaining this and other options: https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61