How to use dependency injection with an attribute?

前端 未结 2 1115
长发绾君心
长发绾君心 2020-11-28 08:55

In an MVC project I\'m creating I have the following RequirePermissionAttribute that gets put on any action that needs specific permissions (it\'s been simplifi

相关标签:
2条回答
  • 2020-11-28 09:37

    What's the best way to inject something into an attribute class?

    Strictly speaking, we cannot use dependency injection to inject a dependency into an attribute. Attributes are for metadata not behavior. [AttributeSpecification()] encourages this by forbidding reference types as arguments.

    What you're probably looking for is to use an attribute and a filter together, and then to inject dependencies into the filter. The attribute adds metadata, which determines whether to apply the filter, and the filter receives the injected dependencies.

    How to use dependency injection with an attribute?

    There are very few reasons to do this.

    That said, if you're intent on injecting into an attribute, you can use the ASP.NET Core MVC IApplicationModelProvider. The framework passes dependencies into the provider's constructor, and the provider can pass dependencies to the attribute's properties or methods.

    In your Startup, register your provider.

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Mvc.ApplicationModels;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;
    
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Transient
                <IApplicationModelProvider, MyApplicationModelProvider>());
    
            services.AddMvc();
        }
    
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
    

    Use constructor injection in the provider, and pass those dependencies to the attribute.

    using System.Linq;
    using Microsoft.AspNetCore.Mvc.ApplicationModels;
    using Microsoft.AspNetCore.Mvc.Routing;
    
    public class MyApplicationModelProvider : IApplicationModelProvider
    {
        private IUrlHelperFactory _urlHelperFactory;
    
        // constructor injection
        public MyApplicationModelProvider(IUrlHelperFactory urlHelperFactory)
        {
            _urlHelperFactory = urlHelperFactory;
        }
    
        public int Order { get { return -1000 + 10; } }
    
        public void OnProvidersExecuted(ApplicationModelProviderContext context)
        {
            foreach (var controllerModel in context.Result.Controllers)
            {
                // pass the depencency to controller attibutes
                controllerModel.Attributes
                    .OfType<MyAttribute>().ToList()
                    .ForEach(a => a.UrlHelperFactory = _urlHelperFactory);
    
                // pass the dependency to action attributes
                controllerModel.Actions.SelectMany(a => a.Attributes)
                    .OfType<MyAttribute>().ToList()
                    .ForEach(a => a.UrlHelperFactory = _urlHelperFactory);
            }
        }
    
        public void OnProvidersExecuting(ApplicationModelProviderContext context)
        {
            // intentionally empty
        }
    }
    

    Create an attribute with public setters that can receive dependencies.

    using System;
    using Microsoft.AspNetCore.Mvc.Routing;
    
    public sealed class MyAttribute : Attribute
    {
        private string _someParameter;
    
        public IUrlHelperFactory UrlHelperFactory { get; set; }
    
        public MyAttribute(string someParameter)
        {
            _someParameter = someParameter;
        }
    }
    

    Apply the attribute to a controller or an action.

    using Microsoft.AspNetCore.Mvc;
    
    [Route("api/[controller]")]
    [MyAttribute("SomeArgument")]
    public class ValuesController : Controller
    {
        [HttpGet]
        [MyAttribute("AnotherArgument")]
        public string Get()
        {
            return "Foobar";
        }
    }
    

    The above demonstrates one way, for the rare use case, that you can inject dependencies into an attribute. If you figure out a valid reason to do this, please post it in the comments.

    0 讨论(0)
  • 2020-11-28 09:47

    I originally thought this was not possible, but I stand corrected. Here's an example with Ninject:

    http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx

    Update 2016-10-13

    This is a pretty old question by now, and frameworks have changed quite a bit. Ninject now allows you to add bindings to specific filters based on the presence of specific attributes, with code like this:

    // LogFilter is applied to controllers that have the LogAttribute
    this.BindFilter<LogFilter>(FilterScope.Controller, 0)
         .WhenControllerHas<LogAttribute>()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to actions that have the LogAttribute
    this.BindFilter<LogFilter>(FilterScope.Action, 0)
         .WhenActionHas<LogAttribute>()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to all actions of the HomeController
    this.BindFilter<LogFilter>(FilterScope.Action, 0)
         .WhenControllerTypeIs<HomeController>()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to all Index actions
    this.BindFilter(FilterScope.Action, 0)
         .When((controllerContext,  actionDescriptor) =>
                    actionDescriptor.ActionName == "Index")
         .WithConstructorArgument("logLevel", Level.Info);
    

    This is in keeping with the principle, argued by Mark Seeman and by the author of Simple Injector, which is that you should keep the logic of your action filter separate from the custom attribute class.

    MVC 5 and 6 also make it far easier to inject values into attributes than it used to be. Still, separating your action filter from your attribute is really the best approach to take.

    0 讨论(0)
提交回复
热议问题