user1178376
user1178376

Reputation: 978

Castle Windsor Generic Typed Factory

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

Answers (2)

Brandon Bonds
Brandon Bonds

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

Cristian Lupascu
Cristian Lupascu

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 lit­er­ally no effort you can use it to build a generic ser­vice 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:

Gen­eral rule of thumb when using IoC con­tain­ers is – when you’re ref­er­enc­ing your con­tainer in your com­po­nents (any­where out­side of your boot­strap­ping code) you’re doing it wrong. As with all rules there are excep­tions, but they are rare.

Upvotes: 1

Related Questions