42

Does Castle Windsor permit registration of an open generic interface or do I need to register each possible typed instance separately?

Example - the below with types T,Z fails upon compilation unless I separately specify T, Z with strong types.

 container.Register(Component
      .For<IAdapterFactory<T,Z>>()
      .ImplementedBy<AdapterFactory<T,Z>>()
      .LifeStyle.PerWebRequest);
Steven
  • 166,672
  • 24
  • 332
  • 435
goldfinger
  • 1,105
  • 1
  • 20
  • 29
  • "Strong types" not an accurate description since templating does use strong types in C#. My point is that Castle Windsor does not seem to accept templates for registration, so it would seem I need to enumerate all possible types within ConstrollerInstaller.cs in order to register the same IAdapterFactory against multiple possible typed invokations. Seems strange. – goldfinger Sep 10 '12 at 02:31
  • it's not Windsor's limitation, it's how .NET runtime works. – Krzysztof Kozmic Sep 10 '12 at 02:52
  • Can you say more about this? "it's not Windsor's limitation, it's how .NET runtime works" – goldfinger Sep 10 '12 at 03:15
  • You cannot close a generic method (like `Component.For<>`) over a non-closed generic type. This is how .NET generics work. Have a look here for some more insight http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx – Krzysztof Kozmic Sep 10 '12 at 04:02

1 Answers1

80

It's called open generic, and yes, Windsor does support that.

 container.Register(Component
             .For(typeof(IAdapterFactory<,>))
             .ImplementedBy(typeof(AdapterFactory<,>))
             .LifestylePerWebRequest());
Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • 1
    One word: wow. Thank you! Just out of curiosity, wonder why Castle folks decided to deviate from more standard C# syntax - instead of <,>? – goldfinger Sep 10 '12 at 03:10
  • 13
    This is the only syntax that will work in this scenario and it has noting to do with Windsor. This just is how you obtain an instance of `System.Type` representing an open generic type. – Krzysztof Kozmic Sep 10 '12 at 03:59
  • 1
    Probable the fifth time this answer helped me out - thank you – Richard Bailey Jan 27 '21 at 07:39