zoukankan      html  css  js  c++  java
  • 使用 windsor 实现IOC 和 AOP

     代码很简单,不多说。

    对于拦截,windsor 使用动态代理的方式,即生成继承类的方式来实现的,因此无法拦截private 方法,因为无法在继承类中看见private方法。

    using System;
    using System.Reflection;
    using Castle.Core;
    using Castle.DynamicProxy;
    using Castle.MicroKernel.Registration;
    using Castle.Windsor;
    
    namespace WindsorSample
    {
        public class ApplicationInterceptor : IInterceptor
        {
            #region IInterceptor Members
    
            public void Intercept(IInvocation invocation)
            {
                Console.WriteLine("call started " + invocation.Method.Name);
                invocation.Proceed();
                Console.WriteLine("call ended " + (invocation.ReturnValue ?? "NULL"));
            }
    
            #endregion
        }
    
        public interface IUserApplication
        {
            void Show();
        }
    
        public class UserApplication : IUserApplication
        {
            private static IUserResoistory _userResoistory;
    
            public UserApplication(IUserResoistory userResoistory)
            {
                _userResoistory = userResoistory;
            }
            public void Show()
            {
                Console.WriteLine(_userResoistory.Name);
            }
        }
    
        public interface IUserResoistory
        {
            string Name { get; }
        }
    
        public class UserResoistory : IUserResoistory
        {
            public string Name { get; private set; }
    
            public UserResoistory()
            {
                Name = "UserResoistory";
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                IWindsorContainer container = new WindsorContainer();
                container.Register(Classes.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn<IUserResoistory>().WithServiceAllInterfaces());
                container.Register(Component.For<IInterceptor>().ImplementedBy<ApplicationInterceptor>().Named("myinterceptor"));
                container.Register(Component.For<IUserApplication>().ImplementedBy<UserApplication>().Interceptors(InterceptorReference.ForKey("myinterceptor")).Anywhere);
    
                var userApplication = container.Resolve<IUserApplication>();
    
                userApplication.Show();
    
                Console.ReadKey();
            }
        }
    }
  • 相关阅读:
    Android接入WebView
    james邮件服务器部署
    防止网络攻击的方式
    vue开发遇到的问题及解决方式
    jekins和docker的作用
    设计模式(2)[JS版]---JavaScript如何实现单例模式?
    黑客帝国中代码雨如何实现?用 canvas 轻松实现代码雨炫酷效果!
    什么是JavaScript 的闭包???
    纯CSS实现iOS风格打开关闭选择框
    纯CSS实现自定义单选框和复选框
  • 原文地址:https://www.cnblogs.com/slardar1978/p/4213296.html
Copyright © 2011-2022 走看看