欢迎来到银龙的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

Unity实现IOC

定义

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace xgbfw.Infrastructure.Aop
{
    public class Ioc
    {
        private static readonly IUnityContainer container;
        private static Dictionary<Type, Type> types;
        private static object lock_obj = new Object();
        static Ioc()
        {
            types = new Dictionary<Type, Type>();
            container = new UnityContainer();
            container.AddNewExtension<Interception>();
        }


        public static TFrom get<TFrom, TTo>() where TTo : TFrom
        {
            lock (lock_obj)
            {
                if (!types.ContainsKey(typeof(TFrom)))
                {
                    types.Add(typeof(TFrom), typeof(TTo));

                    //InterfaceInterceptor
                    container.RegisterType<TFrom, TTo>(new Interceptor<InterfaceInterceptor>(),
                        new InterceptionBehavior<PolicyInjectionBehavior>());
                }

                return container.Resolve<TFrom>();    
            }
        }


    }
}

应用

var result = Ioc.get<IAlertInfoService, AlertInfoService>().Get(getId());

var result = Ioc.get<ISysconfigService, SysconfigService>().Delete(getIds());

 

posted on 2020-06-12 16:44  银龙科技  阅读(327)  评论(0编辑  收藏  举报

导航