• Autofac 设置方法拦截器的两种方式


    前提

    1.Nuget安装Autofac 4.0以下版本  4.0及4.0 以上版本暂时没找到合适的方案

    2.Nuget安装Autofac.Extras.DynamicProxy2

    3.创建一个类似下面代码得 拦截类

        public class TestInterceptor : IInterceptor
        {
            public void Intercept(IInvocation invocation)
            {
                string c = string.Format("Calling method {0} with parameters {1}... ",
         invocation.Method.Name,
         string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));
    
                invocation.Proceed();
    
                string b = string.Format("Done: result was {0}.", invocation.ReturnValue);
            }
        }

    注:autufac文档

    http://docs.autofac.org/en/latest/advanced/interceptors.html

    第一种方式

    在接口或者实现类添加[Intercept(typeof(TestInterceptor))]标签

    如:

       [Intercept(typeof(TestInterceptor))]
        public interface IPersonRepository
        {
            IEnumerable<Person> GetAll();
            Person Get(int id);
            Person Add(Person item);
            bool Update(Person item);
            bool Delete(int id);
        }

    添加注入代码的时候这样写:

    builder.RegisterType<PersonRepository>().EnableInterfaceInterceptors().As<IPersonRepository>();
    
    builder.RegisterType<TestInterceptor>();

    第二种 

    不用添加[Intercept(typeof(TestInterceptor))]标签

    添加注入代码的时候这样写:

    builder
    .RegisterType<PersonRepository>()
    .EnableInterfaceInterceptors()
    .InterceptedBy(typeof(TestInterceptor))
    .As<IPersonRepository>();

    好了  结束

  • 相关阅读:
    Design:目录
    前端框架:template
    Template-ArtTemplate:artTemplate.js
    开发框架:AdminLTE
    开发框架:目录
    杂项:短网址
    httpd
    Java实现洛谷 P1428 小鱼比可爱
    Java实现洛谷 P1428 小鱼比可爱
    java实现洛谷P1308统计单词数
  • 原文地址:https://www.cnblogs.com/liuyu7177/p/5941662.html
Copyright © 2020-2023  润新知