1

尝试使用 Castle Windsor 创建参数化实例时,传递通用参数似乎存在问题

未能通过通用参数的演示

    private static void Main(string[] args)
    {
        PassGenericParamAtResolutionTime();
        Console.ReadLine();
    }

    private static void PassGenericParamAtResolutionTime()
    {
        Console.WriteLine("Passing generic argument fails");
        var container = new WindsorContainer();
        container.Register(Component.For<ISandCoordinator<Simpleton>>()
                           .ImplementedBy<SandCoordinator<Simpleton>>());
        var runtimeConstructorParam = new GenericManager<Simpleton>(
                                          "This Id Does Not Get Through");
        var runtimeArguments = new Arguments(
                                   new object[] {runtimeConstructorParam});
        var shouldBeParameterizedCoordinator = container
                   .Resolve<ISandCoordinator<Simpleton>>(runtimeArguments);
        Console.WriteLine(shouldBeParameterizedCoordinator.Log);
    }

控制台输出

Passing generic argument fails
Birth from parameterless constructor, which should not happen

如果我注释掉下面的无参数构造函数,我会得到以下异常:

Castle.MicroKernel.Resolvers.DependencyResolverException was unhandled
Missing dependency.
Component Sand.SandCoordinator`1[[Sand.Simpleton, WindsorSand, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] has a dependency on Sand.IGenericManager`1[Sand.Simpleton], which could not be resolved.
Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.

带有两个构造函数的演示类

class SandCoordinator<TSimpleton> : ISandCoordinator<TSimpleton>
                                    where TSimpleton : ISimpleton
{
    public SandCoordinator()
    {
        Log = "Birth from parameterless constructor, which should not happen";
    }

    public SandCoordinator(IGenericManager<TSimpleton> manager)
    {
        Log = "Birth from parameterized constructor";
        Log += Environment.NewLine + "Born With Manager: " + manager.Id;
    }        

    public string Log { get; private set; }
}

解决方案/解决方法?

  • 我知道如果我创建一个非泛型类型interface ISimpleSandCoordinator : ISandCoordinator<Simpleton>并注册非泛型接口,那么参数化解析就可以工作,但我不想停止使用泛型类型
  • 这应该作为温莎城堡的错误提交吗?

[使用 Castle.Core.dll 和 Castle.Windsor.dll 3.1.0 (2012-08-05) ]

4

1 回答 1

4

你的SandCoordinator<T>依赖IGenericManager<T>,不是GenericManager<T>

When you're putting a value in Arguments that you want Windsor to use as something else than its concrete type you have to be explicit about it.

new Arguments { { typeof(IGenericManager<Simpleton>), runtimeConstructorParam } };
于 2013-01-28T23:03:09.330 回答