• 程序猿多个对象的友好管理方式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

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

  • 相关阅读:
    python 将字符串转化为可执行代码
    NGS的duplicate的问题
    建库原理
    生信转岗心得
    openpyxl模块处理excel文件
    getopt两个模块getopt 和gun_getopt 的异同
    Migrate repo from Gitlab to Github
    flume(2)
    flume
    docker命令总结
  • 原文地址:https://www.cnblogs.com/yanghucheng/p/15411066.html
Copyright © 2020-2023  润新知