0

I have very simple question that how can I resolve dependency in custom attributes

public class CustomRouteAttribute : Attribute, IRouteTemplateProvider
    {
        string serverKey = string.Empty;

        // Parameterised constructor
        // Need to resolve it automatically without passing it explicitly
        public CustomRouteAttribute(IConfiguration configuration)
        {
            serverKey = configuration.GetSection("serverkey").Value;
        }

        public string Template => $"api/{serverKey}/[controller]";

        public int? Order { get; set; }

        public string Name { get; set; }
    }

I know without parameterised constructor I can use it without any problem like this:

    [CustomRoute]
    [ApiController]
    public class DemoController : ControllerBase
    {
        // Code....
    }

So my question is: How can I use dependency injection in custom attributes.

I know there could be a way like we do in custom filters. We can use dependency injection in our custom filter and use it with TypeFilterAttribute or ServiceFilterAttribute

Example [TypeFilter(typeof(ExampleActionFilter))]

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Voodoo
  • 1,550
  • 1
  • 9
  • 19
  • TypeFilter/ServiceFilter implement [IFilterFactory](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.ifilterfactory?view=aspnetcore-2.1) – Sir Rufo Feb 28 '20 at 16:09
  • Does this help? https://stackoverflow.com/questions/4102138/how-to-use-dependency-injection-with-an-attribute – Athanasios Kataras Feb 28 '20 at 17:22
  • The question which is tagged as similar is not for `.Net Core` and I am not using any third party container to resolve dependencies like `Unity` – Voodoo Feb 28 '20 at 17:42

0 Answers0