C#单例服务中两种接口Id实现的行为差异解析
两种接口Id属性实现方式的差异(单例服务场景下)
在Singleton(单例)服务场景中,以下两种接口Id属性的实现行为完全不同:
第一种实现:只读属性的字段初始化
Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid();
- 行为:所有请求获取该属性时,都会得到相同的Guid,符合单例服务的预期。
- 原理:该写法在类实例构造阶段完成属性初始化,单例服务在应用生命周期内仅创建一次实例,因此
Guid.NewGuid()只会执行一次,后续所有访问都返回这个已生成的Guid。
第二种实现:表达式体属性
public Guid Id => Guid.NewGuid();
- 行为:每次请求获取该属性时,都会生成并返回新的Guid。
- 原理:表达式体属性的
get访问器会在每次属性被访问时执行右侧表达式。即使是单例服务,每次访问Id属性都会触发Guid.NewGuid()调用,因此每次返回的Guid都不相同。
相关代码定义
IReportServiceLifetime.cs
public interface IReportServiceLifetime { Guid Id { get; } ServiceLifetime Lifetime { get; } }
IExampleSingletonService.cs
public interface IExampleSingletonService : IReportServiceLifetime { ServiceLifetime IReportServiceLifetime.Lifetime => ServiceLifetime.Singleton; }
ExampleSingletonService.cs
internal sealed class ExampleSingletonService : IExampleSingletonService { Guid IReportServiceLifetime.Id { get; } = Guid.NewGuid(); // public Guid Id => Guid.NewGuid(); }
通过多次获取单例服务并访问Id属性,可验证上述两种实现的不同行为。
内容的提问来源于stack exchange,提问作者Abhishek Vyas
相关产品推荐
相关产品推荐

