这绝对是 MVVMLight 的 SimpleIoc 中的一个 bug。我已经用 LinqPad 尝试过,问题是当你向类添加一个静态字段时,字段初始化程序会添加一个静态 ctor。
结果是 SomeClass 类有两个用于 SimpleIoc 的 ctor,这会导致您描述的异常。
一种解决方法是向类添加一个默认构造函数并用 装饰它,PreferredConstructorAttribute
但这将导致对 SimpleIoc 的依赖。
其他解决方案是将静态字段更改为常量值。
public class SomeClass
{
private const int staticField = 10;
}
或者使用 Register 方法的重载来为实例创建提供工厂方法。
SimpleIoc.Default.Register<SomeClass>(() => new SomeClass())
我已经在 CodePlex 上提交了一份关于 MVVM Light 项目的错误报告
LinqPad(测试代码):
void Main()
{
var x = GetConstructorInfo(typeof(SomeClass));
x.Dump();
x.IsStatic.Dump();
}
public class PreferredConstructorAttribute : Attribute{
}
public class SomeClass{
private static int staticField = 10;
}
private ConstructorInfo GetConstructorInfo(Type serviceType)
{
Type resolveTo = serviceType;
//#if NETFX_CORE
var constructorInfos = resolveTo.GetTypeInfo().DeclaredConstructors.ToArray();
constructorInfos.Dump();
//#else
// var constructorInfos = resolveTo.GetConstructors();
//constructorInfos.Dump();
//#endif
if (constructorInfos.Length > 1)
{
var preferredConstructorInfos
= from t in constructorInfos
//#if NETFX_CORE
let attribute = t.GetCustomAttribute(typeof (PreferredConstructorAttribute))
//#else
// let attribute = Attribute.GetCustomAttribute(t, typeof(PreferredConstructorAttribute))
//#endif
where attribute != null
select t;
preferredConstructorInfos.Dump();
var preferredConstructorInfo = preferredConstructorInfos.FirstOrDefault ( );
if (preferredConstructorInfo == null)
{
throw new InvalidOperationException(
"Cannot build instance: Multiple constructors found but none marked with PreferredConstructor.");
}
return preferredConstructorInfo;
}
return constructorInfos[0];
}
// Define other methods and classes here
问题是线路
var constructorInfos = resolveTo.GetTypeInfo().DeclaredConstructors.ToArray();
它返回一个包含 2 个 ConstructorInfos 的数组,这两个 ConstructorInfos 均未定义导致异常的 PreferredConstructorAttribute。