0

I have class, which I use to register as GlobalFilter to handle execpions. I register it on global.asax, there everything is all right.
When exception occurs in my action, I enter in OhException method and get NullReference exception, becouse LogManager property is null.

Why nInject doesn't inject it?

public class HandleErrorFilterAttribute : HandleErrorAttribute
{
    [Inject]
    public ILogManager LogManager { get; set; }

    public override void OnException(ExceptionContext filterContext)
    {
        LogManager.LogError("Unhandled exception thrown", filterContext.Exception);

        base.OnException(filterContext);
    }
}

This code below service injection (I forgot write about it)

kernel.Bind<ILogManager>().To<LogManager>();

And there I create object

    public void RegisterGlobalFilters()
    {
        var handleErrorAttribute = new HandleErrorFilterAttribute();
        GlobalFilters.Filters.Add(handleErrorAttribute);
    }
Jacek
  • 11,661
  • 23
  • 69
  • 123
  • 2
    By default, attributes are created by the CLR, not by your DI library. A DI library can only inject dependencies in objects that it creates itself, or when you tell it explicitly to 'build up' this object. So what exactly did you configure that makes you think that Ninject should inject this property? – Steven Feb 10 '15 at 20:53
  • Have you read the docs? Have you looked at [this](https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-filters) specifically? Have you looked at [this SO entry](http://stackoverflow.com/questions/5078046/ninject-and-mvc3-dependency-injection-to-action-filters) which covers your question? – BatteryBackupUnit Feb 11 '15 at 06:13
  • @Steven: Thanks for your comment, I support me to better understand DI, I create instanse by new keywork, so this makes problem. Paste your comment as answer, I will mark it as solution – Jacek Feb 16 '15 at 07:13

1 Answers1

1

By default, attributes are created by the CLR, not by your DI library. A DI library can only inject dependencies in objects that it creates itself, or when you tell it explicitly to 'build up' this object. So in case you new up objects yourself or let the CLR create attributes, the DI library has no chance in injecting dependencies into it.

Steven
  • 166,672
  • 24
  • 332
  • 435