未能通过温莎城堡的通用参数
本文关键字:城堡 参数 | 更新日期: 2023-09-27 17:56:08
尝试使用温莎城堡创建参数化实例时,传递泛型参数似乎存在问题
无法传递泛型参数的演示
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) ]
你的SandCoordinator<T>
取决于IGenericManager<T>
,而不是GenericManager<T>
。
当你在Arguments
中放置一个值时,你希望温莎将其用作其具体类型以外的其他东西,你必须明确说明它。
new Arguments { { typeof(IGenericManager<Simpleton>), runtimeConstructorParam } };