大部分程序猿都有对象太多不好管理的烦恼,这里推荐使用对象容器进行管理,在需要某个对象的时候,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(); });
}
}
初始化类注册对象到容器;对象的生命周期: 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;
}
}
}
希望帮到了各位有很多对象的程序员们