.net core 3.1拡張Autofac AOP

2987 ワード

.net core 3.1拡張Autofac AOP


交流QQ群:555913397何か問題があったら、みんなと一緒に交流しましょう.

1.Nugetパッケージの追加

1.1 Autofac.Extras.DynamicProxy

2.カスタムAOP拡張クラスの追加

    //  Autofac     
    public class AutofacAopExtension : IInterceptor
    {
        //      
        public void Intercept(IInvocation invocation)
        {
            //         
            Console.WriteLine("   ");
            //      
            invocation.Proceed();
            //         
            Console.WriteLine("   ");
        }
    }

3.カスタムAOP拡張の登録

public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //     AOP  
            builder.Register(x => new AutofacAopExtension());

            System.Reflection.Assembly serviceAssembly = System.Reflection.Assembly.Load("CoreMvc.Service");
            System.Reflection.Assembly InterfaceAssembly = System.Reflection.Assembly.Load("CoreMvc.Interface");
            builder.RegisterAssemblyTypes(serviceAssembly, InterfaceAssembly)
            .Where(x => x.Name.EndsWith("AppService", StringComparison.OrdinalIgnoreCase))
            //    ,          ,      ,               
            //1.     
            .EnableClassInterceptors()
            //2.      
            .EnableInterfaceInterceptors()
            //        AOP,        
            .InterceptedBy(typeof(AutofacAopExtension))
            .AsImplementedInterfaces();
        }
    }

4.ブロッキング特性を追加してAOPを実現する

//           
[Intercept(typeof(AutofacAopExtension))]
    public class PeopleAppService : IPeopleAppService
    {
        public void Show()
        {
            Console.WriteLine("People");
        }
    }
}

5.テストAOP

public class HomeController : Controller
    {
        private readonly ILogger _logger;
        private readonly IPeopleAppService _people;
        private readonly ICompanyAppService _company;

        public HomeController(ILogger logger, IPeopleAppService people, ICompanyAppService company)
        {
            _logger = logger;
            _people = people;
            _company = company;
        }

        public IActionResult Index()
        {
            //     
            _people.Show();
            _company.Show();
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

6.使用効果


実行前People実行後実行前Company実行後