在 Xamarin Forms 中注入 CRUD 服务

Injection of CRUD service in Xamarin Forms

我尝试为我尝试新平台 Xamarin Forms。基于 .Net Core 和 EF Core 知识,我决定开始在 Visual Studio 2019 中包含的 Xamarin Forms Shell 模板中注入 Sqlite ORM 服务 (sqlite-net-pcl)。在这个模板中已经实现了基于内存数据结构的 Mock CRUD 服务,所以我想实现我自己的服务并用 DependencyService 注入它。 起初我修改了具有所需属性的数据模型:

public class Item
{
    [PrimaryKey, AutoIncrement]
    public string Id { get; set; }
    public string Text { get; set; }
    public string Description { get; set; }
}

接下来我实现了CRUD服务:

public class SqliteDataStore : IDataStore<Item>
{
    private readonly SQLiteConnection _db;

    public SqliteDataStore()
    {
        _db = new SQLiteConnection(Path.Combine(FileSystem.AppDataDirectory, "items.sqlite"));
        _db.CreateTable<Item>();
        if (_db.Table<Item>().Count().Equals(0))
        {
            _db.InsertAll(new List<Item>
            {
                new Item { Id = Guid.NewGuid().ToString(), Text = "First item", Description = "This is the first item description." },
                new Item { Id = Guid.NewGuid().ToString(), Text = "Second item", Description = "This is the second item description." },
                new Item { Id = Guid.NewGuid().ToString(), Text = "Third item", Description = "This is the third item description." }
            }
            );
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        _db.Insert(item);
        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItem(string id)
    {
        _db.Delete<Item>(id);
        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(_db.Get<Item>(id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(_db.Table<Item>().ToList());
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        _db.Update(item);
        return await Task.FromResult(true);
    }
}

接下来我更改了应用程序中的注入服务class:

public App()
{
    InitializeComponent();

    DependencyService.Register<SqliteDataStore>();
    MainPage = new AppShell();
}

此实现在 Xamarin Forms 中与 EF Core 一起正常工作,但 EF Core 非常慢,所以我更改了 ORM (sqlite-net-pcl) 但它不起作用。

dependency servicee的文档中说:

Important

Registration with the Register methods must be performed in platform projects, before the functionality provided by the platform implementation is invoked from shared code.

所以,我认为您在错误的地方添加了行 DependencyService.Register<SqliteDataStore>();

解决方案:

例如在iOS中应该是:

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        DependencyService.Register<SqliteDataStore>();

        return base.FinishedLaunching(app, options);
    }
}

在Android中:

protected override void OnCreate(Bundle savedInstanceState)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(savedInstanceState);

    DependencyService.Register<SqliteDataStore>();


    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
}

还有Store Data in a Local SQLite.NET Database and Using SQLite.NET with Android的文档可以参考