传递通用参数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>
并注册非泛型接口,那么参数化解析可以工作,但我不想停止使用泛型类型[Using Castle.Core.dll and Castle.Windsor.dll 3.1.0 (2012-08-05)]
答案 0 :(得分:4)
您的SandCoordinator<T>
取决于IGenericManager<T>
,而不是GenericManager<T>
。
当您在Arguments
中放置一个值,您希望Windsor使用其他东西而不是其具体类型时,您必须明确它。
new Arguments { { typeof(IGenericManager<Simpleton>), runtimeConstructorParam } };