在这个问题上绞尽脑汁无济于事,想知道是否有人可以提供帮助?
遇到一个非常令人沮丧的铸造问题,我肯定会有一个快速的答案,但可能只是由于我对泛型类型推断或其他东西的理解有限而发生的。
提前致谢!
场景是向导站点的许多“步骤”视图模型。我正在为每个创建 Builder 类,并使用工厂来获取特定的构建器,以获取回发给我的步骤,这是 IStepViewModel 的集合。
public interface IStepViewModelBuilderFactory
{
IStepModelBuilder<T> Create<T>(T stepViewModel) where T : IStepViewModel;
void Release<T>(IStepModelBuilder<T> stepViewModelBuilder) where T : IStepViewModel;
}
public interface IStepViewModel
{
}
public interface IStepModelBuilder<TStepViewModel> : IModelBuilder<TStepViewModel> where TStepViewModel : IStepViewModel
{
}
public class SpecificViewModelBuilder : IStepModelBuilder<SpecificStepViewModel>
{
}
public class SpecificStepViewModel: StepViewModel
{
}
public abstract class StepViewModel : IStepViewModel
{
}
失败的测试!
[Test]
public void TestResolution()
{
var factory = this.container.Resolve<IStepViewModelBuilderFactory>();
IStepViewModel viewModel = new SpecificStepViewModel();
var builder = factory.Create(viewModel); // Here
Assert.That(builder, Is.Not.Null);
}
问题!
无法将“Company.Namespace.SpecificViewModelBuilder”类型的对象转换为“Company.Namespace.Builders.IStepModelBuilder`1[Company.Namespace.IStepViewModel]”。
工厂实现如下使用 Castle.Windsor
public class StepViewModelSelector : DefaultTypedFactoryComponentSelector
{
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var arg = arguments[0].GetType();
var specType = typeof(IModelBuilder<>).MakeGenericType(arg);
return specType;
}
}
本次登记:
container.AddFacility<TypedFactoryFacility>();
....
container
.Register(
Classes
.FromAssemblyContaining<StepViewModelSelector>()
.BasedOn<StepViewModelSelector>());
container
.Register(
Component
.For<IStepViewModelBuilderFactory>()
.AsFactory(c => c.SelectedWith<StepViewModelSelector>()));
堆栈跟踪:
System.InvalidCastException 未被用户代码处理
HResult=-2147467262 消息=无法将类型为“Company.Namespace.SpecificViewModelBuilder”的对象转换为类型“Company.Namespace.IStepModelBuilder`1[Company.Namespace.IStepViewModel]”。Source=DynamicProxyGenAssembly2 StackTrace: at Castle.Proxies.IStepViewModelBuilderFactoryProxy.Create[T](T stepViewModel) at Tests.Infrastructure.ViewModelBuilderFactoryTests.TestResolution() in c:\Project\Infrastructure\ViewModelBuilderFactoryTests.cs:line 61
InnerException:
编辑:IModelBuilder<T>
界面
public interface IModelBuilder<TViewModel>
{
TViewModel Build();
TViewModel Rebuild(TViewModel model);
}