/// <summary> /// Resolves an instance for the specified type /// </summary> /// <param name="serviceType">Type to resolve</param> /// <param name="name">Name of the registration</param> /// <returns>Returns an instance of an object assignable to serviceType</returns> public object GetService(Type serviceType, string name) { var index = new FactoryIndex(serviceType, name); if (this.factories.TryGetValue(index, out Func <IDependencyResolver, object> factory)) { return(factory(this)); } var baseResult = this.BaseResolver.GetService(serviceType); if (baseResult != null) { return(baseResult); } if (serviceType.IsClass && serviceType.GetConstructors().Length != 0) { var meth = this.constructorFactory.GetType().GetMethod(nameof(ConstructorFactory.Create)); var factoryMethod = meth.MakeGenericMethod(serviceType); var resultFactory = (Func <IDependencyResolver, object>)factoryMethod.Invoke(this.constructorFactory, null); if (this.factories.TryAdd(index, resultFactory)) { return(resultFactory(this)); } } throw new NotSupportedException(); }
/// <summary> /// Registers a type using a specified type as target /// </summary> /// <typeparam name="TFor">Type to register for</typeparam> /// <typeparam name="TTo">Type to register to</typeparam> /// <param name="name">Name of the registration</param> public void Register <TFor, TTo>(string name = null) where TFor : class where TTo : class { var fac = this.constructorFactory.Create <TTo>(); this.factories.TryAdd(FactoryIndex.Create <TFor>(name), fac); }
/// <summary> /// Registers a type factory for the specified name and type /// </summary> /// <typeparam name="T">Type to register</typeparam> /// <param name="factory">Factory method to use when the type is resolved</param> /// <param name="name">Name of the registration</param> public void Register <T>(Func <IDependencyResolver, T> factory, string name) where T : class { this.factories.TryAdd(FactoryIndex.Create <T>(name), factory); }
/// <summary> /// Registers an instance of type T with the specified name /// </summary> /// <typeparam name="T">Type to register</typeparam> /// <param name="instance">Instane to register for the specified type</param> /// <param name="name">Name to use for the registration</param> public void Register <T>(T instance, string name) where T : class { this.factories.TryAdd(FactoryIndex.Create <T>(name), ir => instance); }