8

Castle Windsor just came out with a Fluent interface for registering components as an alternative to using XML in a config file. How do I use this Fluent interface to register a Generic interface?

To illustrate, I have:

public interface IFoo<T,U>
{    
  public T IToo();   
  public U ISeeU(); 
}

Which is implemented by some class called Foo. Now, if I want to register this, I do something like...

var _container = new WindsorContainer();
_container.Register(...);

How do I proceed in registering with this? The procedure for doing the non-generic interface does not work.

Phil
  • 2,143
  • 19
  • 44

2 Answers2

15

Someting like this?

   container.Register(AllTypes.FromAssemblyContaining<YourClass>()
        .BasedOn(typeof(IFoo<,>))
        .WithService.AllInterfaces()
        .Configure(c => c.LifeStyle.Transient));

interface

 public interface IFoo<T, U>
{
    T IToo();
    U ISeeU();
}
danyolgiax
  • 12,798
  • 10
  • 65
  • 116
4

It is unclear in your question whether you need to map the open generic IFoo<T,U> interface one or more implementations that each implement a closed version of that interface (batch registration), or you want to map the open generic interface to an open generic implementation.

Danyolgiax gave an example of batch registration. Mapping an open generic interface to an open generic implementation, gives you the ability to request a closed version of that interface and return a closed version of the specified implementation. The registration for mapping an open generic type would typically look like this:

container.Register(Component
    .For(typeof(IFoo<,>))
    .ImplementedBy(typeof(Foo<,>)));

You can resolve this as follows:

var foo1 = container.Resolve<IFoo<int, double>>();
object foo2 = container.Resolve(typeof(IFoo<string, object>));

As you can can see, you can resolve any closed version of the open generic interface.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • Good point. I was looking for any solution; I just need it working. The thought is to get it working now and modify if need be later. That is why I left the approach open. Thanks for the insight though. – Phil Jun 05 '11 at 13:47
  • Please, show me an example of how to Resolve this via windsor. When I try, the issue is that Foo itself is not generic, so I get an exception like this => System.InvalidOperationException: Fooing.Foo is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true. – Phil Jun 05 '11 at 15:07