Beispiel #1
0
        /// <summary>
        /// Resolve object by type
        /// Get object from cache is as binded as single
        /// Or build with component's options
        /// </summary>
        /// <param name="type">Type to resolve</param>
        /// <param name="id">Custom bind id</param>
        object GetByType(Type type, string id)
        {
            IDIComponent component = default(IDIComponent);

            for (int i = 0; i < _components.Count; i++)
            {
                if (_components[i].ContainsType(type))
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        if (string.IsNullOrEmpty(_components[i].Id) || !_components[i].Id.Equals(id))
                        {
                            continue;
                        }
                        component = _components[i];
                        break;
                    }
                    component = _components[i];
                    break;
                }
            }
            if (component == null)
            {
                throw new Exception($"Can't find bind for type '{type.Name}' and id = '{id}'");
            }
            return(GetByScope(component));
        }
Beispiel #2
0
        /// <summary>
        /// Get component from cache or build
        /// </summary>
        /// <param name="component">Component to build</param>
        object GetByScope(IDIComponent component)
        {
            switch (component.Scope)
            {
            case ScopeMode.Default:
                return(Build(component));

            case ScopeMode.AsSingle:
                if (!_cache.ContainsKey(component.Type))
                {
                    _cache.Add(component.Type, Build(component));
                }
                return(_cache[component.Type]);

            default:
                return(null);
            }
        }
Beispiel #3
0
 /// <summary>
 /// Build object with component's options
 /// </summary>
 /// <param name="component">Component to build</param>
 object Build(IDIComponent component)
 {
     if (component.Construction.HasFlag(ConstructionMode.FromInstance))
     {
         if (component.Instance == null)
         {
             throw new Exception($"Instance is NULL for type '{component.Type.Name}' and id = '{component.Id}'");
         }
         return(component.Instance);
     }
     if (component.Construction.HasFlag(ConstructionMode.WithArguments))
     {
         if (component.Arguments == null)
         {
             throw new Exception($"Arguments is NULL for type '{component.Type.Name}' and id = '{component.Id}'");
         }
         return(Activator.CreateInstance(component.Type, component.Arguments));
     }
     return(Activator.CreateInstance(component.Type));
 }