ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

程序猿多个对象的友好管理方式IOC容器

2021-10-15 15:00:34  阅读:130  来源: 互联网

标签:容器 container 对象 BinLocationReposity return Container IOC public 友好


 大部分程序猿都有对象太多不好管理的烦恼,这里推荐使用对象容器进行管理,在需要某个对象的时候,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

 

 

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

标签:容器,container,对象,BinLocationReposity,return,Container,IOC,public,友好
来源: https://www.cnblogs.com/yanghucheng/p/15411066.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有