/// <summary> /// Resolve an object of type. /// </summary> /// <param name="type">Type of object to resolve.</param> public object Resolve([NotNull] Type type) { bool found = TryFindBindings(type, out var foundBindings); if (!found || foundBindings.Count <= 0) { throw new KeyNotFoundException($"Could not find binding for type: {type}"); } object instance; bool invalidType = false; var firstBinding = foundBindings[0]; if (firstBinding.injected) { instance = firstBinding.instance; if (!type.IsInstanceOfType(instance)) { invalidType = true; } } else { instance = CreateNewInstance(firstBinding); if (type.IsInstanceOfType(instance)) { //inject ContainerDatabase.GetInjector(type)?.Invoke(instance, this); if (firstBinding.scope == Binding.ScopeTypes.Unset) { throw new InvalidOperationException($"Undefined Scope for binding of type: {type}"); } //mark injected if singleton if (firstBinding.scope == Binding.ScopeTypes.Singleton) { firstBinding.instance = instance; firstBinding.injected = true; } } else { invalidType = true; } } if (invalidType) { throw new InvalidCastException( $"Binding for type: {type} has an instance value of type {instance.GetType()}"); } return(instance); }
/// <summary> /// Try and inject an object. /// </summary> /// <param name="obj">The object to inject.</param> /// <returns>Was there an registered injector for the given object.</returns> public bool TryInject(object obj) { var injector = ContainerDatabase.GetInjector(obj.GetType()); if (injector != null) { injector.Invoke(obj, this); return(true); } return(false); }
private object CreateNewInstance(Binding binding) { object instance; if (binding.instance != null) { instance = binding.instance; } else if (binding.instanceFactory != null) { instance = binding.instanceFactory.Invoke(this); } else { var factory = ContainerDatabase.GetFactory(binding.concreteType); instance = factory.Invoke(this); } return(instance); }