Well, I still haven't used Unity, so my answer is rather vague.
The principal is simple. You define some delegates that are factories. Then you create a factory class that has public methods appropriate for delegates. This class knows the container. You will now register the delegate and set this class as an implementation. Then you can enter only the delegate. When you call an indexed delegate, the factory class is called, which knows the container and requests the container for a new instance.
First you define your factory -delegates.
public delegate TServiceType Provider<TServiceType>(); public delegate TServiceType Provider<TArg,TServiceType>(TArg argument);
A common factory is created:
/// <summary> /// Represents a <see cref="Provider{TArg,TServiceType}"/> which holds /// the container context and resolves the service on the <see cref="Create"/>-call /// </summary> internal class GenericFactory{ private readonly IContainer container; public ClosureActivator(IContainer container) { this.container= container; } /// <summary> /// Represents <see cref="Provider{TServiceType}.Invoke"/> /// </summary> public TService Create() { return container.Resolve<TService>(); } /// <summary> /// Represents <see cref="Provider{TArg,TServiceType}.Invoke"/> /// </summary> public TService Create(TArg arg) { return container.Resolve<TService>(new[] {new TypedParameter(typeof (TArg),arg)}); } }
Now that you register the delegate, something like this:
var newServiceCreater = new GenericFactory(container); container.Register<Provider<MyCompoent>>().To(newServiceCreater.Create); var newServiceCreater = new GenericFactory(container); container .Register<Provider<OtherServiceWithOneArgumentToConstruct>>() .To(newServiceCreater.Create);
Now you add only the Provider to the other components instead of the container.
source share