8
votes

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.

2

2 Answers

15
votes

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();
}
4
votes

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.