在Autofac中为同一类型选择多个注册

时间:2013-07-02 13:23:20

标签: c# .net asp.net-mvc dependency-injection autofac

我正在使用带有Autofac的MVC4开发一个Web应用程序。我有一个全局异常过滤器,我正在注入一个记录器服务,所以我在App_Start中初始化它,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(DependencyResolver.Current.GetService<IExceptionFilter>());
    }

这是过滤器的总体布局:     公共类ErrorHandlerAttribute:HandleErrorAttribute     {         private readonly ILoggerService logger;

    public ErrorHandlerAttribute(ILoggerService logger)
    {
        this.logger = logger;
    }

    public override void OnException(ExceptionContext filterContext)
    {
        //dostuff
    }

    public void LogError(ExceptionContext context)
    {
        try
        {
            logger.Error(context.Exception.Message, context.Exception);
        }
        catch (Exception) { }
    }
}

如果我没有使用Autofac,我会有类似的东西:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorHandlerAttribute());

        filters.Add(new ErrorHandlerAttribute
        {
            View = "UnauthorizedException",
            ExceptionType = typeof(UnauthorizedAccessException)
        });

        filters.Add(new ErrorHandlerAttribute
        {
            View = "PageNotFound",
            ExceptionType = typeof(NotImplementedException)
        });
    }

ErrorHandlerAttribute是我的自定义异常过滤器,派生自MVC的HandleErrorAttribute。

我希望能够保留重定向到自定义错误页面的能力,同时使用Autofac的注入和单个过滤器(因为我构建它以便它可以处理任何异常)。 不幸的是,我似乎无法找到任何方法来做到这一点,尽管在网络和其他论坛上寻找可能的解决方案。我已经尝试了很多配置更改,不同的注册,集合解析等。

我希望它的工作方式与此类似:

    builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>().InstancePerHttpRequest();
    builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
        .WithProperties(new List<NamedParameter>() { new NamedParameter("ExceptionType", typeof(UnauthorizedAccessException)), new NamedParameter("View", "UnauthorizedAccess") })
        .InstancePerHttpRequest();
    builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
        .WithProperties(new List<NamedParameter>() { new NamedParameter("ExceptionType", typeof(NotImplementedException)), new NamedParameter("View", "UnderConstruction") })
        .InstancePerHttpRequest();
    builder.RegisterFilterProvider();

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        DependencyResolver.Current.GetServices<IExceptionFilter>().ForEach(f => filters.Add(f));
    }

令人惊讶的是,这会编译并运行,但所有3个IExceptionFilter实例都是正常的,默认的ErrorHandlerAttribute(使用View =“Error”和ExceptionType = typeof(object))。

我知道Autofac默认使用服务的最后一次注册,我尝试评论三次注册中的两次,以及使用PreserveExistingDefaults,我的所有异常过滤器都带有默认值。

我是否误解了WithProperties扩展方法,还是有其他类似方法来实现我想要的东西?

编辑1

感谢Alex的建议,我通过使用NamedPropertyParameter并切换语句的顺序来解决它:

builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
    .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(UnauthorizedAccessException)), new NamedPropertyParameter("View", "UnauthorizedAccess") })
    .InstancePerHttpRequest();
builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
    .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(NotImplementedException)), new NamedPropertyParameter("View", "UnderConstruction") })
    .InstancePerHttpRequest();
builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>().InstancePerHttpRequest();

1 个答案:

答案 0 :(得分:5)

您需要使用NamedPropertyParameter代替NamedParameter

builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
    .SingleInstance();
builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
    .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(UnauthorizedAccessException)), new NamedPropertyParameter("View", "UnauthorizedAccess") })
    .SingleInstance();
builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>()
    .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(NotImplementedException)), new NamedPropertyParameter("View", "UnderConstruction") })
    .SingleInstance();

您也可以将全局过滤器注册为SingleInstance,因为它们已经过解析,然后直接添加到过滤器集合中。 MVC不会根据HTTP请求请求这些过滤器的实例。它只会使用您添加到集合中的实例。