Autofac属性属性注入不起作用

时间:2014-11-12 09:42:09

标签: c# asp.net-web-api autofac

我检查了这些答案:

但是,我的代码看起来设置正确但属性注入不起作用。

这是我的Autofac注册:

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;
}

我的属性是:

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

    public override void OnException(HttpActionExecutedContext filterContext) { }
}

但是,logService为null。有什么问题?

修改

我根据下面的评论更改了属性,因此属性类现在看起来像这样:

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

    public void OnException(HttpActionExecutedContext filterContext) { }
}

我还必须删除过滤器添加到WebApiConfig中的config.Filters。

我改变了Autofac注册:

builder.RegisterWebApiFilterProvider(config);

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

但是,现在我收到以下异常(可能是Autofac尝试找到过滤器):

对象引用未设置为对象的实例。&#34;,&#34;键入&#34;:&#34; System.NullReferenceException&#34;,&#34; stacktrace&#34;:&# 34;在System.Linq.Enumerable.d__14的System.Web.Http.Controllers.HttpActionDescriptor.b__0(IFilterProvider fp)\ r \ n的Autofac.Integration.WebApi.AutofacWebApiFilterProvider.GetFilters(HttpConfiguration配置,HttpActionDescriptor actionDescriptor)\ r \ n中2.MoveNext(个)\ r \ n
等...等等......

0 个答案:

没有答案