未能通过Castle Windsor传递通用参数

时间:2013-01-27 16:43:06

标签: c# .net dependency-injection castle-windsor constructor-injection

传递通用参数when attempting to create a parametrized instance with 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 Windsor的一个错误吗?

[Using Castle.Core.dll and Castle.Windsor.dll 3.1.0 (2012-08-05)]

1 个答案:

答案 0 :(得分:4)

您的SandCoordinator<T>取决于IGenericManager<T>,而不是GenericManager<T>

当您在Arguments中放置一个值,您希望Windsor使用其他东西而不是其具体类型时,您必须明确它。

new Arguments { { typeof(IGenericManager<Simpleton>), runtimeConstructorParam } };