Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in ExceptionFilterAttribute C#

I am using Castle Windsor in my application and I would like to use inject some services example ILog in my ExceptionFilterAttribute :

public class GenericExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly ILog _logger;

    public GenericExceptionFilterAttribute()            
    {

    }

    public GenericExceptionFilterAttribute(ILogManager logManager)
    {
        _logger = logManager.GetLogger(typeof(GenericExceptionFilterAttribute));
    }
}

How can I inject services in this class ?

Regards

Carlos

like image 598
user3511244 Avatar asked Mar 17 '15 12:03

user3511244


People also ask

Can we use dependency injection in .NET framework?

NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Dependency injection in . NET is a built-in part of the framework, along with configuration, logging, and the options pattern.

Can we inject dependency in Viewcomponent?

A view component class: Supports constructor dependency injection. Doesn't take part in the controller lifecycle, therefore filters can't be used in a view component.

What is injection dependency C#?

Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

Can we inject IServiceCollection?

Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services. You can inject an instance of type IServiceProvider into any method of a class.


1 Answers

Hi the dependencyResolver to solve this :

 public override void OnException(HttpActionExecutedContext context)
                {
                    var log= (ILog)context.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(ILog));    
                }
like image 73
user3511244 Avatar answered Sep 20 '22 17:09

user3511244