/// <summary> /// 根据对应关系获取实体 /// </summary> /// <param name="relation"></param> /// <returns></returns> public object Get(TypeRelation relation) { //如果注册时提供了对象则直接适用对象 if (relation.Instance != null) { return(relation.Instance); } //如果注册时提供了Func<ISeriveProvider,object>用于生成对象则调用Func else if (relation.Factory != null) { return(relation.Factory.Invoke(this.serviceProvider)); } //如果在对应关系中存在serviceType则根据构造函数生成对象 else if (this.typeRelations.ContainsServiceType(relation.ServiceType)) { return(CreateByConstructor(relation.ImplementType)); } //检查泛型情况 else if (relation.ServiceType.IsConstructedGenericType) { if (relation.ServiceType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { return(CreateIEnumerable(relation.ServiceType)); } else { return(CreateGeneric(relation.ServiceType)); } } //暂时没想到这种情况,先扔个异常 else { return(null); } }
/// <summary> /// 在容器中根据对照关系获取对象 /// </summary> /// <param name="key"></param> /// <param name="relation"></param> /// <returns></returns> private object GetRecordObject(string key, TypeRelation relation) { //如果存在则直接返回 if (recordObjects.Contains(key)) { return(objects[key]); } //不存在则生成一个 else { var obj = this.objectFactory.Get(relation); recordObjects.Add(key); if (objects.TryAdd(key, obj)) { this.objectIndex.Add(key); return(obj); } //如果添加失败说明其他线程已经添加了对象(因为key唯一) //直接返回容器中的对象 else { return(objects[key]); } } }
/// <summary> /// 根据对照关系获取对象 /// </summary> /// <param name="relation"></param> /// <returns></returns> public object Get(TypeRelation relation) { var key = relation.ID; //如果是Singleton对象则直接在根容器中查找 if (relation.Lifetime == ServiceLifetime.Singleton) { return(root.GetRecordObject(key, relation)); } //Scoped容器在当前容器中查找 else if (relation.Lifetime == ServiceLifetime.Scoped) { return(GetRecordObject(key, relation)); } //Transient对象直接生成 else { //随便生成一个Key避免重复 key = key + Guid.NewGuid().ToString().GetHashCode(); var obj = this.objectFactory.Get(relation); if (this.objects.TryAdd(key, obj)) { this.objectIndex.Add(key); } return(obj); } }
/// <summary> /// 当前依赖关系能否创建实例 /// </summary> /// <param name="relation"></param> /// <returns></returns> public bool CanCreateInstance(TypeRelation relation) { if (relation.CanSelfBuild) { return(true); } return(CanCallConstructor(relation.ImplementType)); }
/// <summary> /// 直接获取ImplementSerivce对象 /// </summary> /// <param name="typeRelation"></param> /// <returns></returns> public object GetServiceByRelation(TypeRelation typeRelation) { return(this.objectContainer.Get(typeRelation)); }