我正在关注YouTube N=2: Kittens and Lists
上的教程当KittenView
点击OnCreate()
Cirrious.CrossCore.Exceptions.MvxException:无法从定位器MvxDefaultViewModelLocator加载类型MyApp.Core.ViewModels.KittenViewModel的ViewModel
似乎它无法解析服务(IKittenGenesisService
),因为当我添加一个空构造函数时,应用程序运行时没有错误。但很明显,如果没有依赖关系,视图将无法正常工作。
同样的解决方案还有一个早期教程,其中包含使用FirstViewModel
的{{1}}。这个服务解析得很好并且运行,所以我知道MVVM IoC正在运行。但我发现两者之间没有任何区别。我无法调试到PCL项目没有帮助,但这是一个不同的问题。
ICalculationService
然而这些工作正常:
public class App: MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
RegisterAppStart<KittenViewModel>();
}
}
[Activity(Label = "View for KittenViewModel")]
public class KittenView : MvxActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.KittenView);
}
}
public class KittenViewModel: MvxViewModel
{
public KittenViewModel(IKittenGenesisService service)
{
var kittenList = new List<Kitten>();
for (var i = 0; i < 100; i++)
{
var newKitten = service.CreateNewKitten(i.ToString());
kittenList.Add(newKitten);
}
Kittens = kittenList;
}
private List<Kitten> _kittens;
public List<Kitten> Kittens
{
get { return _kittens; }
set
{
_kittens = value;
RaisePropertyChanged(() => Kittens);
}
}
}
public class KittenGenesisService: IKittenGenesisService
{
private readonly List<string> _names;
private readonly Random _random;
public KittenGenesisService()
{
_random = new Random();
_names = new List<string>()
{
"Tiddles",
"Amazon",
"Pepsi",
"Solomon",
"Butler",
"Snoopy",
"Harry",
"Holly",
"Paws"
};
}
public Kitten CreateNewKitten(string extra = "")
{
return new Kitten()
{
Name = _names[Random(_names.Count)] + extra,
ImageUrl = string.Format("http://placekitten.com/{0}/{0}"),
Price = RandomPrice()
};
}
public int Random(int count)
{
return _random.Next(count);
}
public int RandomPrice()
{
return Random(23) + 3;
}
}
这是我添加的单元测试,当它尝试新建[Activity(Label = "View for FirstViewModel")]
public class FirstView : MvxActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
}
}
public class FirstViewModel: MvxViewModel
{
private readonly ICalculationService _calculationService;
public FirstViewModel(ICalculationService calculationService)
{
_calculationService = calculationService;
_generosity = 20;
_subTotal = 100;
Recalc();
}
// more code
}
时会立即引发空引用异常,KittenViewModel
构造函数被称为正常。
KittenGenesisService
答案 0 :(得分:3)
我认为如果基本知识可能值得检查一下:
如果这些东西看起来不错,那么可能值得尝试一些调试技术:
Mvx.CanResolve<IKittenGenesisService>()
是否返回true?