Castle Windsor - IoC registration for open generic interfaces?
Asked Answered
H

1

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);
Hominy answered 10/9, 2012 at 2:24 Comment(4)
"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.Hominy
it's not Windsor's limitation, it's how .NET runtime works.Diligence
Can you say more about this? "it's not Windsor's limitation, it's how .NET runtime works"Hominy
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 msdn.microsoft.com/en-us/library/b8ytshk6.aspxDiligence
D
80

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

 container.Register(Component
             .For(typeof(IAdapterFactory<,>))
             .ImplementedBy(typeof(AdapterFactory<,>))
             .LifestylePerWebRequest());
Diligence answered 10/9, 2012 at 2:50 Comment(3)
One word: wow. Thank you! Just out of curiosity, wonder why Castle folks decided to deviate from more standard C# syntax - <T,Z> instead of <,>?Hominy
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.Diligence
Probable the fifth time this answer helped me out 🙄 - thank youEnrika

© 2022 - 2024 — McMap. All rights reserved.