Reputation: 978
On Kozmic's blog (dated 2009), he recommends a Generic Factory to retrieve objects from container. Well, this seems like a pseudo service locator to me. So I want to ask the opinion from experts here.
public interface IGenericFactory
{
T Create<T>();
}
Can I use this to fetch objects from Windsor container? Are there any downsides to this approach?
Update:
Actually, I want to use it to get only a few transients that I do not want to create multiple factories for. Having one factory for all such scenarios.
Upvotes: 0
Views: 4028
Reputation: 203
Instead, consider the following:
public interface IGenericFactory<out T>
{
T Create();
}
The interface only needs to be created once, but it must be injected for each service you need to resolve. This way, it isn't a generic service locator (which is an antipattern, as previously mentioned by w0lf).
Bonus points:
Normal dependency injection requires that all services in your dependency graph can be resolved. IGenericFactory<>
will automatically be resolved via the typed factory facility. But its generic type argument will not be resolved until executing Create()
.
If that happens in an edge case deep in your program, and you forget to register the service, you might not realize the bug until production.
The solution is to write a custom resolver for IGenericFactory<>
that checks whether the generic type argument has a handler and that it is not waiting for any dependencies to be registered. Information about custom resolvers is here: http://docs.castleproject.org/Windsor.Resolvers.ash
Upvotes: 1
Reputation: 40576
I did a quick Google search and found this article that you're probably referring to: http://kozmic.pl/2009/12/23/castle-typed-factory-facility-reborn/
If that's the case, then Krzysztof Koźmic says it himself:
[...] with literally no effort you can use it to build a generic service locator.
Yes, nowadays Service Locator is considered to be an anti-pattern.
However, the article is about exceptional cases. The author puts it quite clearly in the first paragraph:
General rule of thumb when using IoC containers is – when you’re referencing your container in your components (anywhere outside of your bootstrapping code) you’re doing it wrong. As with all rules there are exceptions, but they are rare.
Upvotes: 1