2

I checked these answers:

However, my code looks correctly set up but the property injection is not working.

This is my Autofac registration:

public static AutofacWebApiDependencyResolver Setup()
{
    var config = GlobalConfiguration.Configuration;
    var builder = new ContainerBuilder();

    builder.Register(x => new LogService())
        .As<ILogService>()
        .SingleInstance();

    builder.RegisterType<ExceptionHandlingAttribute>().PropertiesAutowired();

    var container = builder.Build();
    var resolver = new AutofacWebApiDependencyResolver(container);

    GlobalConfiguration.Configuration.DependencyResolver = resolver;
}

My attribute is this:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
internal class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public ILogService logService { get; set; }

    public override void OnException(HttpActionExecutedContext filterContext) { }
}

However, logService is null. What is the problem?

EDIT

I changed the attribute as per comment below, so the attribute class now looks like this:

internal class ExceptionHandlingAttribute : IAutofacExceptionFilter
{
    public ILogService logService { get; set; }

    public void OnException(HttpActionExecutedContext filterContext) { }
}

I also had to remove the filter from being added to config.Filters in WebApiConfig.

I changed the Autofac registration like this:

builder.RegisterWebApiFilterProvider(config);

builder.RegisterType<ExceptionHandlingAttribute>()
    .AsWebApiExceptionFilterFor<BaseODataController>()
    .InstancePerRequest()
    .PropertiesAutowired();

However, now I'm getting the following exception (probably Autofac tries to locate the filter):

Object reference not set to an instance of an object.","type":"System.NullReferenceException","stacktrace":" at Autofac.Integration.WebApi.AutofacWebApiFilterProvider.GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)\r\n at System.Web.Http.Controllers.HttpActionDescriptor.b__0(IFilterProvider fp)\r\n at System.Linq.Enumerable.d__14`2.MoveNext()\r\n
etc... etc...

Community
  • 1
  • 1
Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • 1
    Autofac won't inject action filters in web.api. You need to use the custom `IAutofacExceptionFilter` as described in the documenation http://autofac.readthedocs.org/en/latest/integration/webapi.html#register-the-filter-provider – nemesv Nov 12 '14 at 09:46

0 Answers0