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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值