简体   繁体   English

在 Xamarin Forms 中注入 CRUD 服务

[英]Injection of CRUD service in Xamarin Forms

I try to experiment with new platform for me, Xamarin Forms.我尝试为我尝试新平台 Xamarin Forms。 Based on.Net Core and EF Core knowledge I decided to begin with injecting Sqlite ORM service (sqlite-net-pcl) in Xamarin Forms Shell template included in Visual Studio 2019. In this template there is already implemented Mock CRUD service based on in-memory data structure so I wanted to implement my own service and inject it with DependencyService. Based on.Net Core and EF Core knowledge I decided to begin with injecting Sqlite ORM service (sqlite-net-pcl) in Xamarin Forms Shell template included in Visual Studio 2019. In this template there is already implemented Mock CRUD service based on in-内存数据结构,所以我想实现自己的服务并用 DependencyService 注入它。 At first I have modified data model with needed attribute:起初我修改了数据 model 所需的属性:

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

Next I implemented CRUD service:接下来我实现了 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);
    }
}

Next I changed injected service in App class:接下来我在 App class 中更改了注入服务:

public App()
{
    InitializeComponent();

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

This implementation properly works with EF Core in Xamarin Forms but EF Core is very slow so I changed ORM (sqlite-net-pcl) and it does not work.此实现与 Xamarin Forms 中的 EF Core 一起正常工作,但 EF Core 非常慢,所以我更改了 ORM(sqlite-net-pcl)并且它不起作用。

In the document of dependency servicee , it says:依赖 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.在从共享代码调用平台实现提供的功能之前,必须在平台项目中执行Register方法的注册。

So, I think you have added the line DependencyService.Register<SqliteDataStore>();所以,我认为你已经添加了DependencyService.Register<SqliteDataStore>(); at a wrong place.在错误的地方。

Solution :解决方案

For example, in iOS it should be:例如,在 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);
    }
}

In Android:在 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());
}

There is also documents about Store Data in a Local SQLite.NET Database and Using SQLite.NET with Android you can refer.还有关于在本地 SQLite.NET 数据库中存储数据将 SQLite.NET 与 Android 一起使用的文档,您可以参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM