Consider the scenario where a service's constructor has a mix of parameters: some you want the container to resolve based on whatever you registered, and some you want the consumer of the service to provide.
With Autofac, one may add a Factory delegate to a service as follows (examples below are taken from their documentation) :
public class Shareholding
{
// We don't have to add the quote service to the factory delegate.
public delegate Shareholding Factory(string symbol, uint holding);
// Parameters in the constructor that don't show up in
// the delegate will come from the appropriate lifetime scope.
public Shareholding(string symbol, uint holding, IQuoteService quoteService)
{
...
}
You register the service "normally":
builder.RegisterType<Shareholding>();
Autofac does some magic, and now the Factory is requestable on consumers. Autofac will supply the missing parameters (IQuoteService in this case) with whatever is registered, if possible, and provide a new instance each time the factory is invoked, e.g.:
public class Portfolio
{
private readonly Shareholding.Factory _shareHoldingFactory;
private readonly List<Shareholding> _holdings = new List<Shareholding>();
public Portfolio(Shareholding.Factory shareholdingFactory)
{
_shareHoldingFactory = shareholdingFactory;
}
public void Add(string symbol, uint holding)
{
_holdings.Add(_shareHoldingFactory(symbol, holding));
}
}
Does Simple Injector have something similar to this? I have gone around in circles considering and trying a few things:
- Registering an, e.g.,
Func<string, uint, QuoteService>
won't work because then I'll need to requestFunc<string, uint, QuoteService>
on my consumers instead of just QuoteService.Factory, which will be annoying if it's used in more than one place and the parameters are changed. - I don't really want to create factory wrappers for all my services. Having been spoilt by Autofac, this just seems like too much overhead now.
- The
Register<TService>(Func<TService> instanceCreator)
overload won't work because the Func doesn't take parameters and there isn't an overload for one that does (right?)
I feel like I'm missing something obvious because this is such a useful feature.