温莎城堡:使用约定注册和特定的实现 [英] Castle Windsor: Using convention registration along with specific implementations

查看:61
本文介绍了温莎城堡:使用约定注册和特定的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有Foo实现的IFoo和FirstBar和SecondBar实现的IBar。

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

使用此约定注册:

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

容器中将有三个条目:

IFoo = Foo
IBar = FirstBar
IBar = SecondBar

现在,我们如何调整此注册以告诉容器对于IBar我们只希望SecondBar注册?

Now, how can we tweak this registration to be able to tell the container that for IBar we want SecondBar registered only? Sort of:

container.Register(
    AllTypes.FromThisAssembly().Pick()
        .WithService.DefaultInterface()
        .For<IBar>().Select<SecondBar>())

用例:我们的应用程序中有很多服务都是按照惯例注册的。但是,某些服务接口具有两个或多个实现(例如,实际实现,伪实现和测试实现)。约定注册会将它们全部注册在同一接口下,而在解析接口时,我们将获得第一个实现(不确定的顺序)。我们希望能够在注册时为这些服务选择一种特定的实现。

Use case: we have lots of services in our app all registered by conventions. However, some of the service interfaces have two or more implementations (e.g. real implementation, fake implementation and test implementation). Convention registration will register them all under the same interface and while resolving the interface we'll get the first implementation (in nondeterministic order). We want to be able to select one specific implementation for those services while registering. How can we do that?

推荐答案

这是完成工作的原因:

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

这实际上仅注册了IBar服务的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>()

这很好。我相信这两种方法可以在Castle.Windsor中使用。 @KrzysztofKoźmic:我在哪里提交补丁? :)

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

这篇关于温莎城堡:使用约定注册和特定的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆