使用 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();
        }
    }
}

 

posted @ 2015-01-09 14:42  大鱼人  阅读(965)  评论(0编辑  收藏  举报