首页 > 解决方案 > .Net Core 自定义属性中的依赖注入

问题描述

dependency我有一个非常简单的问题,我该如何解决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; }
    }

我知道没有parameterised constructor我可以毫无问题地使用它:

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

所以我的问题是:我如何dependency injectioncustom attributes.

我知道可能有一种方法,就像我们在custom filters. 我们可以在我们的中使用依赖注入custom filter并将其与TypeFilterAttributeServiceFilterAttribute一起使用

例子 [TypeFilter(typeof(ExampleActionFilter))]

标签: c#asp.net-core.net-coredependency-injectionattributes

解决方案


推荐阅读