0
votes

I'm using Castle Windsor to register a number of interfaces each of which can created with a generic factory method. i.e.

container.Register(Component.For(typeof(IFirstService))
    .UsingFactoryMethod(k => GetService<IFirstService>())
    .LifeStyle.Singleton);

container.Register(Component.For(typeof(ISecondService))
    .UsingFactoryMethod(k => GetService<ISecondService>())
    .LifeStyle.Singleton);

Rather than add registration code for each interface, can I use the Types method to register them all in one go (all interfaces derive from IService) eg:

container.Register(Types
    .FromThisAssembly()
    .Where(t => typeof(IService).IsAssignableFrom(t))
    .Configure(c => c.UsingFactoryMethod(k => GetService<?>()));
1

1 Answers

0
votes

Because generic method calls a usually set up by the compiler you can't exactly do that at runtime without invoking using reflection, however with an object GetService(Type t) signature instead of a generic argument you can do this:

container.Register(Types.FromThisAssembly()
    .BasedOn<IService>()
    .Configure(c =>
        c.UsingFactoryMethod((k, ctx) => GetService(ctx.RequestedType))
    )
);

This is using the UsingFactoryMethod overload that provides the CreationContext.