0

I have an application and pass some dependency injection things (logger for example):

    ILog _logger;
    _logger = new NLogService.NLogService();
    if (serviceType == typeof(OCRAPIController))
        return new OCRAPIController(_logger);

    Domain.ILog _logger;

    public OCRAPIController(Domain.ILog logger)
    {
        if (logger == null)
            throw new ArgumentNullException(nameof(logger));

        _logger = logger;
    }

and then use it:

_logger.AddLog(...);

it works and works fine. Problem is with attributes. I.e. I have the following attribute:

public class ReportAPIAccessAttribute : ActionFilterAttribute
{
    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
    {

and I want to log something. Of course, I can't pass ILog as parameter for constructor. I can create static method as wrapper around ILog and call it or even create NLogService.NLogService() directly in attribute. But I don't like both approaches because I want to have only one place in application, where I call NLogService directly. I can create ServiceLocator for attribute, but then other developers (or even I when I forget) can call ServiceLocator in places, where DI parameter should be called...

How to solve this problem correctly?

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • 1
    See [Actionfilter Injection in ASP.NET MVC 5](https://stackoverflow.com/a/28794980/181087) and [Dependency Injection in Attributes: don’t do it!](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98). – NightOwl888 May 23 '17 at 04:19
  • I have read it and not found a response my question. I need to log something in ActionFilter, filter writes to Http response and none place to catch it... – Oleg Sh May 23 '17 at 12:06
  • I don't understand where you are getting hung up. You just need to ditch `ActionFilterAttribute`, inherit `IFilterAttribute`, and you can inject your `ILog` dependency during application startup. Then (optionally) create an attribute to scan for to turn the logging behavior on/off per action or controller. This is *exactly* what MVC does, all you need to do is sidestep the default behavior so you can add your DI container without having a constrained constructor. – NightOwl888 May 23 '17 at 13:31
  • What version of MVC are you using? – NightOwl888 May 23 '17 at 13:31

0 Answers0