Castle Windsor: Using convention registration along with specific implementations

后端 未结 2 460
星月不相逢
星月不相逢 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<IBar>(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<TService, TImpl>(this BasedOnDescriptor desc)
    {
        return desc.ConfigureFor<TService>(c => c.If((k, m) => m.Implementation == typeof(TImpl)));
    }
    
    public static BasedOnDescriptor Ignore<TService>(this BasedOnDescriptor desc)
    {
        return desc.ConfigureFor<TService>(c => c.If((k, m) => false));
    }
    

    We can now use it like this:

    container.Register(
        AllTypes.FromThisAssembly().Pick()
            .WithService.DefaultInterface())
            .Select<IBar, SecondBar>()
            .Ignore<ISomeService>()
    

    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? :)

    0 讨论(0)
  • 2021-01-05 23:23

    Tighten your convention. It is obviously to wide.

    container.Register(
        AllTypes.FromThisAssembly()
            .Where(t => t.Namespace != "Acme.Tests")
            .WithService.DefaultInterface())
    
    0 讨论(0)
提交回复
热议问题