Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Castle Windsor - Fluent Interface to register a generic interfaces?

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.

like image 232
Phil Avatar asked Jun 05 '11 04:06

Phil


2 Answers

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();
}
like image 62
danyolgiax Avatar answered Sep 23 '22 03:09

danyolgiax


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.

like image 39
Steven Avatar answered Sep 19 '22 03:09

Steven