Gabriel Castillo Prada
Gabriel Castillo Prada

Reputation: 4701

Error resolving ActionFilterAttribute as TypeFilter in .net Core 3.1

Updating my application from .Net Core 2.2 to 3.1 I get an error trying to resolve a dependency of an ActionFilter.

I have this filter

public class DoSomethingAttribute : ActionFilterAttribute
    {
        private readonly IWorkContext workContext;

        public OneEnum OneParameter { get; set; }

        public AuthorizeAdminAttribute(OneEnum oneParameter, IWorkContext workContext)
        {
            OneParameter = oneParameter;
            workContext = workContext;
        }

         /**more stuff**/
    }

I registered it

services.AddScoped<DoSomethingAttribute>();

And I called it

    [HttpDelete]
    [Authorize]
    [Route("{id:int}")]
    [TypeFilter(typeof(DoSomethingAttribute), Arguments = new object[] { OneEnum.OneValue } )]
    public async Task<IActionResult> Delete(int id)
    {}

With .Net core 2.2 version it was working but with 3.1 I get this error:

InvalidOperationException: Error while validating the service descriptor 'ServiceType: DoSomethingAttribute Lifetime: Scoped ImplementationType: DoSomethingAttribute': Unable to resolve service for type 'POneEnum' while attempting to activate 'DoSomethingAttribute'.

InvalidOperationException: Unable to resolve service for type 'OneEnum' while attempting to activate 'DoSomethingAttribute'.

Any ideas?

Upvotes: 2

Views: 531

Answers (1)

Rena
Rena

Reputation: 36715

Here is a working demo like below:

public class MyFilterAttribute : TypeFilterAttribute
{
    public MyFilterAttribute(params object[] arguments) : base(typeof(DoSomethingAttribute))
    {
        Arguments = new object[] { arguments };
    }

    public class DoSomethingAttribute : ActionFilterAttribute
    {

        private readonly IWorkContext WorkContext;
        private readonly OneEnum OneParameter;
 
        public DoSomethingAttribute(object[] arguments, IWorkContext workContext)
        {
            OneParameter = (OneEnum)arguments[0];
            WorkContext = workContext;

        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //do your stuff....
             await base.OnActionExecutionAsync(context, next);
        }
    }
}

Add the attribute to Controller:

[MyFilter(OneEnum.OneValue)]
public async Task<IActionResult> Delete(int id)
{}

No need to register the attribute like below:

services.AddScoped<DoSomethingAttribute>();

Upvotes: 2

Related Questions