使用 TypedFactoryFacility 时,我在解析 ITcpServer 时遇到了一些问题。Windsor 似乎没有找到合适的组件从工厂返回该接口。我的案例的具体情况是接口 ITcpServer 是非通用的,而实现它的类都是通用的。
运行时抛出以下代码:
未处理的异常:Castle.MicroKernel.ComponentNotFoundException:在 Castle.Facilities 的 Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(类型服务、IDictionary 参数、IReleasePolicy 策略)中找不到支持服务 ConsoleApplication1.StandardTcpServer`1 的组件.TypedFactory.TypedFactoryComponentResolver.Resolve(IKernelInternal kernel, IReleasePolicy scope) at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Resolve(IInvocation invocation) at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Intercept(IInvocation invocation) at Castle.DynamicProxy。
Castle.Proxies.ITcpServerFactoryProxy.Create[T] 的AbstractInvocation.Proceed() (String serverType, T something)
编码:
class Program
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.Install(new MyWindsorInstaller());
var f = container.Resolve<ITcpServerFactory>();
var tcpServer = f.Create("standard", "something");
tcpServer.Start();
}
}
public class MyWindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ITcpServer>().ImplementedBy(typeof(LibUvTcpServer<>)),
Component.For<ITcpServer>().ImplementedBy(typeof(StandardTcpServer<>)),
Component.For<ITcpServerFactory>().AsFactory(c => c.SelectedWith(new TcpServerComponentSelector()))
);
}
}
public class TcpServerComponentSelector : DefaultTypedFactoryComponentSelector
{
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var serverType = (string)arguments.First();
return serverType == "standard" ? typeof (StandardTcpServer<>) : typeof(LibUvTcpServer<>);
}
}
public interface ITcpServerFactory
{
ITcpServer Create<T>(string serverType, T something);
}
public class StandardTcpServer<T> : ITcpServer
{
public void Start()
{
Console.WriteLine("Started...");
}
}
public class LibUvTcpServer<T> : ITcpServer
{
private readonly T something;
public LibUvTcpServer(T something)
{
this.something = something;
}
public void Start()
{
Console.WriteLine("Started...");
}
}
public interface ITcpServer
{
void Start();
}
解决问题的任何帮助将不胜感激。