让SNAP(AOP),Autofac和ASP.Net MVC 5协同工作

时间:2014-12-22 15:35:22

标签: c# asp.net-mvc-5 aop autofac

我试图让Snap(https://github.com/TylerBrinks/Snap)与MVC 5和Autofac一起使用,以便能够在控制器的操作中使用属性。

我已经能够根据示例使控制台应用程序正常工作,但是当我在MVC中尝试时,我似乎无法实现它。

问题是LoggingInterceptor没有被调用。

这就是我所做的:

配置Autofac和Snap

public static class AutofacConfig
{
    public static void ConfigureAndSetContainerAndAop()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        var autofacContainer = new AutofacAspectContainer(builder);

        SnapConfiguration.For(autofacContainer).Configure(c =>
        {
            c.IncludeNamespace("WebUI.Controllers.*");// Here, if try c.IncludeNamespaceOf<MvcApplication>() I get a NullReferenceException.;
            c.Bind<LoggingInterceptor>().To<LoggingAttribute>();
        });

        DependencyResolver.SetResolver(new AutofacDependencyResolver(autofacContainer.Builder.Build()));

    }
}

属性和拦截器。

public class LoggingAttribute : MethodInterceptAttribute
{
    public LoggingAttribute()
    {

    }
}

public class LoggingInterceptor : MethodInterceptor
{
    private static readonly Logger Logger = LogManager.GetLogger("LoggingInterceptor");

    public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
    {
        Logger.Info("Executing LoggingInterceptor.InterceptMethod()");
        invocation.Proceed();
    }

    public override void BeforeInvocation()
    {
        Logger.Info("Executing LoggingInterceptor.BeforeInvocation()");
        base.BeforeInvocation();
    }

    public override void AfterInvocation()
    {
        Logger.Info("Executing LoggingInterceptor.AfterInvocation()");
        base.AfterInvocation();
    }
}

具有属性的控制器:

public class HomeController : Controller
{

    [Logging]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}

0 个答案:

没有答案