gpt4 book ai didi

c# - 无法通过 CaSTLe Windsor 传递通用参数

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:02 30 4
gpt4 key购买 nike

传递通用参数似乎有问题 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>并注册非通用接口(interface)然后参数化解析工作,但我不想停止使用通用类型
  • 是否应将其作为 CaSTLe Windsor 中的错误提交?

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

最佳答案

你的 SandCoordinator<T>取决于 IGenericManager<T> , 不是 GenericManager<T> .

当您在 Arguments 中输入一个值时您希望 Windsor 用作具体类型以外的其他东西,您必须明确说明。

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

关于c# - 无法通过 CaSTLe Windsor 传递通用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14549577/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com