I'm letting my IoC container manage the life of my object graph and seem to be reusing a particular lifestyle a lot that is not available in the Castle Windsor default set at the moment.
Example
I need to construct objects context-specifically by passing in resolution-time arguments into a factory and when I pass in the string Dorothy for instance, I would like to get back a singleton of Person that would be instantiated with string Dorothy, if it does not exist in the container yet, or otherwise the existing Dorothy instance. Same when passing the string argument Jane into my factory - please return singleton of Person Jane. And there might be Sally, Bob and many others, the complete set of inputs unravelling at runtime only.
Manual Implementation
Here's another example, implemented using a dictionary in my custom class:
private readonly static IDictionary<string,IRecruiter> Recruiters
= new Dictionary<string, IRecruiter>();
private IRecruiter GetRecruiter(string recruiterId)
{
IRecruiter recruiter;
if (!Recruiters.TryGetValue(recruiterId, out recruiter))
{
recruiter = this.donorFactory.CreateRecruiter(recruiterId);
Recruiters.Add(recruiterId,recruiter);
}
return recruiter;
}
And where the donorFactory CreateRecruiter method does something like that:
return this.Create<IRecruiter>(new Arguments { { typeof(string), recruiterId }});
SRP and Reducing Boilerplate
I find I use this pattern a lot, so would like to know if it is somehow possible to implement using existing Castle Windsor lifestyles, or maybe there is a case made to add this pattern to Castle Windsor itself?
- Registering components as .Named does not work in this case as the set of incoming arguments is not known at design-time
- The pattern could have a general implementation that would work with any type of argument (not just string) or even sets of arguments, if GetHashCode or something like that was used as the key for the dictionary.