我已经努力思考,但没有结果。不知道有没有人能够帮忙?
我遇到了一个非常令人沮丧的问题,这个问题应该很快就能解决,但可能是由于我的泛型类型推断的理解有限或其他原因引起的。
提前感谢!
场景是一个向导站点的多个“步骤”ViewModel。我为每个ViewModel创建了构建器类,并使用工厂来获取返回给我的步骤的特定构建器,这是一个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 Message=无法将类型为“Company.Namespace.SpecificViewModelBuilder”的对象转换为类型 “Company.Namespace.IStepModelBuilder`1 [Company.Namespace.IStepViewModel]”。 来源=DynamicProxyGenAssembly2 StackTrace: at Castle.Proxies.IStepViewModelBuilderFactoryProxy.Create[T](T stepViewModel) at Tests.Infrastructure.ViewModelBuilderFactoryTests.TestResolution() in c:\Project\Infrastructure\ViewModelBuilderFactoryTests.cs:line 61
内部异常:
编辑:IModelBuilder<T>
接口
public interface IModelBuilder<TViewModel>
{
TViewModel Build();
TViewModel Rebuild(TViewModel model);
}
IStepModelBuilder<TStepViewModel>
。这个TStepViewModel
真的应该是这样吗? - Steve