【问题标题】:.NET WebAPI Cache Data on Start.NET WebAPI 在启动时缓存数据
【发布时间】:2021-03-10 21:44:03
【问题描述】:

我有一个简单的 .Net WebAPI,我需要在启动时实例化一个类(只需一次)。该实例需要可供每个控制器使用。

如何/在哪里加载应用程序启动时的这些数据(我在哪里创建我的实例)以及如何从每个控制器访问这个实例?我需要 DI 吗?

编辑:运行框架,而不是核心。

【问题讨论】:

  • 你不需要DI,但如果你使用.NET Core,我认为你应该。
  • @Crowcoder,你能详细说明一下吗?

标签: c# .net asp.net-web-api


【解决方案1】:

创建一个单例类并在 startup.cs 中初始化它

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}

private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多