ASP.NET Core 单例总是获得不同的实例

问题描述 投票:0回答:1

我正在尝试创建一个全局对象,并且需要在整个生命周期中保留其值。 但我注意到每次访问该对象时都会获得新的实例。

IProfile
在其他地方没有被引用。

 services.AddSingleton<IProfile, Profile>();

 IProfile currentProfile { get; set; }
 private ILogger logger;

 public MainController(IProfile profile, ILogger<MainController> logger)
 {    
     currentProfile = profile;
     logger.LogInformation("IProfile : " + profile.ProfileName);
     this.logger = logger;
 }

 HttpPost("SelectProfile")]
 public async Task<string> SelectProfile(string profile)
 {
     logger.LogInformation(currentProfile.ProfileName);
     logger.LogInformation(currentProfile.GetHashCode().ToString());

     currentProfile = config.Profiles
                            .Where(p => p.ProfileName == profile).FirstOrDefault();

     if (currentProfile.ProfileName is not null)           
         return "Profile Updated";
     
     logger.LogInformation(currentProfile.ProfileName + " " + currentProfile.GetHashCode());

     return ("Profile not found!!");
 }

如何在生命周期内只获取一个实例?

asp.net-core singleton
1个回答
0
投票

您的个人资料应该是单身人士。您正在使用

GetHashCode()
检查同一实例。但文档说:

...此方法的默认实现不得用作哈希目的的唯一对象标识符。” ValueType 的内容是“如果调用派生类型的 GetHashCode 方法,则返回值不太可能适合用作哈希表中的键。”。

所以最好自己重写

Equals()
GetHashCode()
- 然后就会发现这实际上是同一个实例。

编辑#1: 来自

IOptionsMonitor<Configuration>
的实例从您的
appsettings.json
(或其他配置提供者)反序列化。所以这个实例与您的服务注册无关。所以这些实例必须是不同的。

© www.soinside.com 2019 - 2024. All rights reserved.