【问题标题】:MvxException: Failed to initialize ViewModel for type x from locatorMvxException:无法从定位器初始化类型 x 的 ViewModel
【发布时间】:2019-06-20 22:49:31
【问题描述】:

请来 Xamarin 和 MvvmCross 专家。我一直在尝试调试这个错误几个小时MvvmCross.Exceptions.MvxException: Failed to construct and initialize ViewModel for type TestApp.Core.ViewModels.IngredientsViewModel from locator MvxDefaultViewModelLocator。我找到了实际导致此错误的一段代码,它与使用 EFCore sqlite 从数据库中提取数据有关。

这是我第一次将它用于移动应用程序,所以也许你会发现一些我看不到的东西。以下是我认为足够的所有信息,如果需要更多信息,请告诉我!我希望该解决方案对其他人有所帮助。 请注意,当我注释掉 GetIngredients 时,我没有收到上述错误。

Core/Shared 项目中的我的应用文件

public class AppCore : MvxApplication
{
    public override void Initialize()
    {
        Mvx.IoCProvider.RegisterType<TestContext>();
        Mvx.IoCProvider.RegisterType<IIngredientRepository, IngredientRepository>();
        RegisterAppStart<IngredientsViewModel>();
    }
}

我的 DbContext

public class TestContext : DbContext
{
    public TestContext() : base()
    {
    }
    private const string _databaseName = "Test.db";
    public DbSet<Ingredient> Ingredients { get; set; }    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        string databasePath;
        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
                SQLitePCL.Batteries_V2.Init();
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", _databaseName); ;
                break;
            case Device.Android:
                databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), _databaseName);
                break;
            default:
                throw new NotImplementedException("Platform not supported");
        }
        optionsBuilder.UseSqlite($"Filename={databasePath}");
    }
}

存储库

public interface IRepository<TEntity> where TEntity : class
{
        IEnumerable<TEntity> GetAll();
}

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected readonly TestContext Context;
    public Repository(TestContext context)
    {
        Context = context;
    }

    public IEnumerable<TEntity> GetAll()
    {
        return Context.Set<TEntity>().ToList(); //after this line error is thrown
    }
}

public interface IIngredientRepository : IRepository<Ingredient> {}
public class IngredientRepository : Repository<Ingredient>, IIngredientRepository
{
    public IngredientRepository(TestContext testContext) : base(testContext)
    { }
}

我的视图模型

public class IngredientsViewModel : BaseViewModel
{
    private IIngredientRepository IngredientRepository { get; set; }

    public IngredientsViewModel(IIngredientRepository ingredientRepository)
    {
        IngredientRepository = ingredientRepository;
        GetIngredients(); //when commented out, the view loads fine
    }

    private void GetIngredients()
    {
        var ingredients = IngredientRepository.GetAll();
        Ingredients = new MvxObservableCollection<Ingredient>(ingredients);
    }

    private MvxObservableCollection<Ingredient> _ingredients;
    public MvxObservableCollection<Ingredient> Ingredients
    {
        get => _ingredients;
        set { SetProperty(ref _ingredients, value); }
    }
}

【问题讨论】:

  • 应该有一个内部异常,该异常具有嵌入在该 MvxException 中的更详细的错误消息。你能把那个贴出来吗?我的猜测是您的成分表尚未创建,这就是您在查询该表中的所有项目时遇到错误的原因。
  • @pnavk 你的意思是抛出错误后输出窗口中的信息吗?我看到很多 .db 文件没有找到。我认为这指向了下面的答案。非常感谢!

标签: c# sqlite xamarin xamarin.forms mvvmcross


【解决方案1】:

在您的 TestContext.cs 中,尝试在构造函数中添加以下行:

Database.EnsureCreated(); //returns boolean which could be used for some check if needed

另外,我的建议是覆盖 OnModelCreating 如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        base.OnModelCreating(modelBuilder);

        //creating tables according to UML
        modelBuilder.Entity<Ingredient>();

        //add one for each table
}

如果这没有帮助,请尝试检查 InnerException 或逐步调试。

【讨论】:

  • 太棒了!我的视图现在加载没有问题!我已经在 Android 设备监视器中意识到,即使在输入 Database.EnsureCreated()Database.Migrate() 之后,我的模拟设备也有一个空的数据文件,你会知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 2020-07-12
  • 2018-06-16
  • 1970-01-01
  • 2021-12-20
  • 2014-06-22
  • 2017-04-06
相关资源
最近更新 更多