【问题标题】:How to use XML or JSON as a datasource in ASP.NET core [closed]如何在 ASP.NET 核心中使用 XML 或 JSON 作为数据源 [关闭]
【发布时间】:2017-05-29 20:18:03
【问题描述】:

我想使用 JSON 或 XML 文件将我的数据存储在 ASP.NET 核心应用程序中。
这样做的原因是数据不多,数据变化也不大。优点是提高了应用程序的速度,并且我不需要应用程序的数据库(省钱)。

所以我的想法是将数据序列化为 XML 或 JSON。当应用程序启动时,这些数据应该被加载到内存中。
在更改时,应更新文件。

有没有一种直接的方法可以做到这一点,或者这是一种应该被劝阻的工作方式?

【问题讨论】:

  • 提高了速度?好吧,如果您真的追求速度,您将绕过序列化和反射技术并使用平面文件。但老实说,不要。遗憾的是你的问题太宽泛了。 How to Ask

标签: c# asp.net json xml


【解决方案1】:

无论您决定使用哪种数据存储技术,我都建议您将数据访问抽象为某个接口之后,这样您的应用程序就不会绑定到特定的实现。如果您将来决定改用其他存储技术,这将使您能够更轻松地切换到其他存储技术。

因此,如果您想使用内存数据存储,那么为什么不呢:

public interface IDataStore
{
    IQueryable<MyModel> Get();

    void Add(MyModel model);

    ...
}

可以这样实现:

public JsonDatastore : IDataStore
{
    private readonly string dataFile;
    private readonly IList<MyModel> data;

    public Datastore(string dataFile)
    {
        this.dataFile = dataFile;
        this.data = JsonConvert.DeserializeObject<IList<MyModel>>(File.ReadAllText(dataFile));
    }

    public IQueryable<MyModel> Get()
    {
        return this.data.AsQueryable();
    }

    public void Add(MyModel model)
    {
        // If you want a lock free implementation you may consider
        // an algorithm which will only notify some underlying thread
        // that a change has been made to the underlying structure and
        // it will take care of saving those changes to the file system
        // This way it is guaranteed that only one thread is writing
        // to the file while the changes can be made in memory quite fast
        // (using a ConcurrentBag<T> instead of a list for example)

        lock (this)
        {
            // Make sure that only one thread is updating the file
            this.data.Add(model);
            string json = JsonConvert.SerializeObject(this.data);
            File.WriteAllText(this.dataFile, json);
        }
    }
}

现在最后一点是确保您将依赖注入容器中的 Datastore 生命周期实例配置为 singleton

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2021-07-06
    • 2010-11-26
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多