Castle Windsor: Using convention registration along with specific implementations

后端 未结 2 461
星月不相逢
星月不相逢 2021-01-05 22:51

Assume we have IFoo implemented by Foo and IBar implemented by FirstBar and SecondBar.

Using this convention registration:

container.Register(
    Al         


        
2条回答
  •  逝去的感伤
    2021-01-05 23:21

    This is what made the work done:

    container.Register(
        AllTypes.FromThisAssembly().Pick()
            .WithService.DefaultInterface())
            .ConfigureFor(c => 
                c.If((k, m) => m.Implementation == typeof(SecondBar)));
    

    This effectively registers only SecondBar impl for IBar service. This way, if there is more than one implementation for given service, we can tell the conventional scanner which impl we want.

    We went ahead and created nice little extension methods for this purpose:

    public static BasedOnDescriptor Select(this BasedOnDescriptor desc)
    {
        return desc.ConfigureFor(c => c.If((k, m) => m.Implementation == typeof(TImpl)));
    }
    
    public static BasedOnDescriptor Ignore(this BasedOnDescriptor desc)
    {
        return desc.ConfigureFor(c => c.If((k, m) => false));
    }
    

    We can now use it like this:

    container.Register(
        AllTypes.FromThisAssembly().Pick()
            .WithService.DefaultInterface())
            .Select()
            .Ignore()
    

    All in all this works nicely. I believe those two methods could be in the Castle.Windsor proper. @Krzysztof Koźmic: where do I submit a patch? :)

提交回复
热议问题