InjectionFactory can be Generic

Apr 28, 2010 at 11:45 AM

Hi, it looks like InjectionFactory can be Generic to provide more type safety, and to check factory return type on its registration in the container.
What do you think about this proposal?
Here is draft example of that I am talking about:

	public class InjectionFactory<T> : InjectionMember
	{
		private readonly Func<IUnityContainer, Type, string, T> factoryFunc;
        
		public InjectionFactory(Func<IUnityContainer, T> factoryFunc)
			: this((c, t, s) => factoryFunc(c))
		{
		}

		public InjectionFactory(Func<IUnityContainer, Type, string, T> factoryFunc)
		{
			Guard.ArgumentNotNull(factoryFunc, "factoryFunc");
			this.factoryFunc = factoryFunc;
		}

		public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
		{
			Guard.ArgumentNotNull(implementationType, "implementationType");
			Guard.ArgumentNotNull(policies, "policies");
			Guard.TypeIsAssignable(implementationType, typeof(T), "factoryType");

			var policy = new FactoryDelegateBuildPlanPolicy<T>(factoryFunc);
			policies.Set<IBuildPlanPolicy>(policy,
				new NamedTypeBuildKey(implementationType, name));
		}
	}

	class FactoryDelegateBuildPlanPolicy<T> : IBuildPlanPolicy
	{
		private readonly Func<IUnityContainer, Type, string, T> factory;

		public FactoryDelegateBuildPlanPolicy(Func<IUnityContainer, Type, string, T> factory)
		{
			this.factory = factory;
		}

		public void BuildUp(IBuilderContext context)
		{
			if (context.Existing == null)
			{
				var currentContainer = context.NewBuildUp<IUnityContainer>();
				context.Existing = factory(currentContainer, context.BuildKey.Type, context.BuildKey.Name);

				DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
			}
		}
	}

May 14, 2010 at 8:58 AM

Up, anyone has any ideas about my proposal?