private static void AddFactoryToList <T>( PocketContainer container, Func <PocketContainer, T> factory) { // avoid re-entrancy which would result in a stack overflow if (recursionCounter.Value != 0) { return; } try { recursionCounter.Value++; // register IEnumerable<Func<PocketContainer, T>> container.TryRegister(c => c.Resolve <List <Func <PocketContainer, T> > >() .Select(f => f(c))); // register the registration list as a singleton container.TryRegisterSingle(c => new List <Func <PocketContainer, T> >()); // resolve it and add the factory var registrations = container.Resolve <List <Func <PocketContainer, T> > >(); registrations.Add(factory); } finally { recursionCounter.Value--; } }
/// <summary> /// Registers an open generic type to another open generic type, allowing, for example, IService&T& to be registered to resolve to Service&T&. /// </summary> /// <param name="container">The container.</param> /// <param name="variantsOf">The open generic interface that callers will attempt to resolve, e.g. typeof(IService&T&).</param> /// <param name="to">The open generic type to resolve, e.g. typeof(Service&T&).</param> /// <param name="singletons">If true, each type will be lazily registered as a singleton.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService&T&) /// or /// Parameter 'to' is not an open generic type, e.g. typeof(Service&T&) /// </exception> public static PocketContainer RegisterGeneric(this PocketContainer container, Type variantsOf, Type to, bool singletons = false) { if (!variantsOf.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException("Parameter 'variantsOf' is not an open generic type, e.g. typeof(IService<>)"); } if (!to.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException("Parameter 'to' is not an open generic type, e.g. typeof(Service<>)"); } return(container.AddStrategy(t => { if (t.GetTypeInfo().IsGenericType&& t.GetGenericTypeDefinition() == variantsOf) { var closedGenericType = to.MakeGenericType(t.GetTypeInfo().GenericTypeArguments); if (singletons) { container.TryRegisterSingle( t, cc => cc.Resolve(closedGenericType)); } return c => c.Resolve(closedGenericType); } return null; })); }