小编val*_*tin的帖子

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

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

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(DependencyResolver.Current.GetService<IExceptionFilter>());
    }
Run Code Online (Sandbox Code Playgroud)

这是过滤器的一般布局:public class 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) { }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我没有使用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)
        });
    }
Run Code Online (Sandbox Code Playgroud)

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

我希望能够保持重定向到自定义错误页面的能力,同时使用Autofac的注入和单个过滤器 …

.net c# asp.net-mvc dependency-injection autofac

2
推荐指数
1
解决办法
1685
查看次数

标签 统计

.net ×1

asp.net-mvc ×1

autofac ×1

c# ×1

dependency-injection ×1