zoukankan      html  css  js  c++  java
  • 程序猿多个对象的友好管理方式IOC容器

     大部分程序猿都有对象太多不好管理的烦恼,这里推荐使用对象容器进行管理,在需要某个对象的时候,CALL它;

    使用IOC容器的好处是:解耦了对象之间的强耦合,规范了使用对象的生命周期  缺点:IOC内部使用反射的方式创建对象,会有一定的性能损耗;

     下面用以前用过的对象容器SimpleInjector 举个栗子:

    前期工作: 先使用NuGet引入SimpleInjector  包;

    由于是面向借口编程,所以每个对象都需要接口

         
    //容器对象 
      public class SimpleInjectorDependencyResolver : IDependencyResolver 
        { 
             
            private static readonly Container _container = new Container(); 
      
            public object Container 
            { 
                get { return _container; } 
            } 
            public T Resolve() where T : class 
            { 
                return _container.GetInstance(); 
            } 
            public object Resolve(Type type) 
            { 
                return _container.GetInstance(type); 
            } 
            public Lazy LazyResolve() where T : class 
            { 
                return new Lazy(() => { return Resolve(); }); 
            } 
          
        } 
    View Code
     初始化类注册对象到容器;对象的生命周期: Lifestyle. Scoped :一生一个对象 Transient:每次都是一个新对象 Singleton:单身 
     public partial class IocConfig 
        { 
            public Container _container = (Container)Engine.Resolver.Container; 
            private void System() 
            { 
                _container.Register < IDbContext>(() => 
                { 
                    return new PSADataEntities(DBFactory.ConnectionString); 
                },Lifestyle.Scoped); 
                _container. Register< IUnitOfWork, UnitOfWork> (); 
                _container.Register(typeof(IGenericRepository<>), typeof(GenericRepository<>)); 
            } 
        } 
     取对象 
       public class SomeService : BaseService, IBinLocationService 
        { 
             
            private IGenericRepository _BinLocationReposity; 
            public IGenericRepository BinLocationReposity 
            { 
                get 
                { 
                    if (null == _BinLocationReposity) 
                    { 
                        _BinLocationReposity = Engine.Resolver.Resolve< IGenericRepository< SYS_LOCATION >>(); 
                    } 
                    return _BinLocationReposity; 
                } 
            } 
       }
    View Code

    希望帮到了各位有很多对象的程序员们

  • 相关阅读:
    andrax不为人知的秘密
    SecuritySRT console已经建立链接为什么还没有反应?
    必备软硬件
    关于mt的个人看法及优缺点
    hash是什么
    usb接口的缺点
    古董交换机欣赏
    博客圆低调的文章审核机制
    手机技术控不能买哪些手机,应该买什么手机
    两个以上vlan三台以上交换机配置好,网络不通,引发的思考
  • 原文地址:https://www.cnblogs.com/yanghucheng/p/15411066.html
Copyright © 2011-2022 走看看