[英]Castle Windsor: how to register multiple types as implementing a specific interface?
更新
我有以下类/接口:
public interface IFoo
{
(...)
}
public interface IFoo<T> : IFoo
{
(...)
}
public abstract BaseFoo<T> : IFoo<T>
{
(...)
}
public Bar : BaseFoo<ConcreteType1>
{
(...)
}
public Baz : BaseFoo<ConcreteType2>
{
(...)
}
使用Castle Windsor,如何将Bar和Baz类型注册为实现IFoo?
我已经尝试过一些不成功的事情:
Register(Types.FromAssembly(typeof (IFoo).Assembly)
.BasedOn<IFoo>()
.WithService
.Select(new List<Type> { typeof(IFoo)})
.Configure(x => x.LifeStyle.Is(LifestyleType.Singleton)));
编辑 :评论中陈述的异常表明抽象类BaseFoo
正在尝试解决。 这是因为您使用选择所有组件的Types
,甚至是抽象类。 一个简单的方法来避免这种情况是使用Classes
不存在这个问题。 文件说明:
我应该使用类或类型吗?
按惯例开始注册有两种方法。 其中一个是使用Classes静态类,就像上面的例子一样。 其次是使用类型静态类。 它们都暴露出完全相同的方法。 它们之间的区别在于,类型将允许您注册来自给定程序集的所有(或者确切地说,如果您使用默认设置,所有公共)类型,即类,接口,结构,委托和枚举。 另一方面,类预先过滤类型以仅考虑非抽象类 。 大多数情况下,Classes是您将使用的类,但在某些高级方案中,类型可能非常有用,例如基于接口的类型化工厂的注册。
该代码看起来是正确的-事实上,我尝试了与三个不同的WithService
电话( 基地 AllInterfaces和选择 )和每一个成功。 我认为可能是您选择的第一部分可能不正确: Types.FromAssembly(typeof (IFoo).Assembly)
我没有找到任何方法来获取城堡在尝试使用流畅注册时所考虑的列表,但您可以使用Configure
来记录所考虑组件的名称:
c.Register(Classes.FromAssemblyInThisApplication()
.BasedOn<IFoo>()
.Configure(x => Console.WriteLine(x.Implementation.Name)) // classes names
.WithService.Select(new Type[] {typeof(IFoo)})
.Configure(x => x.LifeStyle.Is(LifestyleType.Singleton)));
因此,请尝试检查您是否使用了正确的程序集,或者您的类是否对容器可见
编辑
此代码有效:
public interface IFoo
{
}
public interface IFoo<T> : IFoo
{
}
public abstract class BaseFoo<T> : IFoo<T>
{
}
public class Bar : BaseFoo<Bar>
{
}
public class Baz : BaseFoo<Baz>
{
}
// main
var c = new Castle.Windsor.WindsorContainer();
c.Register(Classes.FromAssemblyInThisApplication()
.BasedOn<IFoo>()
.Configure(x => Console.WriteLine(x.Implementation.Name))
.WithService.Select(new Type[] {typeof(IFoo)})
.Configure(x => x.LifeStyle.Is(LifestyleType.Singleton)));
var all = c.ResolveAll<IFoo>(); // 2 components found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.