我的 MVC 应用程序中有以下代码可以正常工作。
container.Register(Component.For<CountryServiceBase>()
.ImplementedBy<CountryService>()
.LifestylePerWebRequest());
CaSTLe Windsor 创建一个组件
CountryService / CountryServiceBase
我的 Controller 在这里获取一个实例化对象:
public class MyController : MainController
{
public CountryServiceBase CountryService {get; set;} // instantiate by Ioc : OK
我的问题是我有很多类(class)要注册。所以我使用 CaSTLe Windsor 做了以下事情:
container.Register(
Types
.FromAssemblyNamed("mynamespace")
.BasedOn(typeof(ServiceBase<>))
.WithService.Base()
.LifestylePerWebRequest());
CaSTLe Windsor 创建我的组件
CountryService / ServiceBase<Country>
CountryServiceBase / ServiceBase<Country>
但是我的 MVC 应用程序等待 CountryService/CountryServiceBase,我不知道如何向 CaSTLe Windsor 指定它可以将 CountryServiceBase 匹配回 CountryService,因为这两个类(其中一个是抽象类)继承了 ServiceBase
有可能吗?
注意:我发布了一个类似的问题,但我的调查得出了一个更准确的问题,所以我删除了旧的问题。
最佳答案
通常 services是接口(interface)。这就是为什么 AllInterfaces()
为别人工作。
如果您检查 API,您会发现 Select()
易于使用的方法。
If none of the above options suits you you can provide your own selection logic as a delegate and pass it to
WithService.Select()
method.
所以注册码可以是这样的:
container.Register(Types.FromThisAssembly()
.BasedOn(typeof(ServiceBase<>))
.WithService.AllInterfaces()
.WithService.Select((t, b) => t.BaseType != null
? new[] { t.BaseType }
: new Type[0])
.LifestylePerWebRequest());
此解决方案非常快捷,但至少可以解决您的问题。
关于c# - CaSTLe Windsor 注册匹配相同服务的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806393/