美文网首页dotNET
Autofac的简单封装

Autofac的简单封装

作者: czly | 来源:发表于2017-02-15 09:42 被阅读0次

    将Autofac集成到自己的框架项目中,对Autofac进行了简单的封装,方便调用。
    <pre>
    public class IocHelper
    {
    private static IContainer _Container;

        public static IContainer Container
        {
            get 
            {
                if (_Container == null)
                {
                    _Container = _Build.Build();
                }
                return _Container; 
            }
        }
    
    
        private static ContainerBuilder _Build ;
    
        public static ContainerBuilder CurrentBuild
        {
            get 
            { 
                return _Build;
            }
        }
    
        static IocHelper()
        {
            _Build = new ContainerBuilder();
        }
    
        public static void Register<T>()
        {
            _Build.RegisterType<T>();
        }
    
        public static void Register<T,T1>()
        {
            _Build.RegisterType<T>().As<T1>();
        }
    
        public static void Register(object obj)
        {
            _Build.RegisterInstance(obj);
        }
    
        public static void RegisterAssembly(Assembly assembly)
        {
            _Build.RegisterAssemblyTypes(assembly);
        }
    
        public static void RegisterAssemblys(Assembly[] Assemblys)
        {
            _Build.RegisterAssemblyTypes(Assemblys);
        }
    
        public static T Resolve<T>(string name)
        {
            return Container.ResolveNamed<T>(name);
        }
    
        public static T Resolve<T>()
        {
            return Container.Resolve<T>();
        }
    }
    

    </pre>

    调用方法如下
    <pre>
    IocHelper.Register<ClassA,IClassA>();

            IocHelper.RegisterAssembly(Assembly.GetExecutingAssembly());
    
            IClassA ca = IocHelper.Resolve<IClassA>();
            ClassB cb = IocHelper.Resolve<ClassB>();
    

    </pre>

    相关文章

      网友评论

        本文标题:Autofac的简单封装

        本文链接:https://www.haomeiwen.com/subject/nvgmittx.html