ASP.NET 4.8单例上下文类依赖注入实现及属性设计疑问
改造方案
1. 提取抽象接口
首先定义IMyCustomContext接口,把你需要对外暴露的所有成员都声明在接口中:
public interface IMyCustomContext { IMyCustomContext Current { get; } HttpContext Context { get; } User LoggedInUser { get; } Collection<SiteWideSettings> SiteWideSettings { get; } }
2. 改造原有MyCustomContext类
让原有单例类实现IMyCustomContext接口,原有逻辑完全保留,只需要补充接口成员的实现即可,也可以保留原有静态成员兼容旧代码:
public sealed class MyCustomContext : IMyCustomContext { private static readonly Lazy<MyCustomContext> staticContext = new Lazy<MyCustomContext>(() => new MyCustomContext()); private MyCustomContext() { } // 原有静态成员保留,兼容旧代码调用 public static MyCustomContext Current => staticContext.Value; // 实现接口的Current属性 IMyCustomContext IMyCustomContext.Current => staticContext.Value; public HttpContext Context => HttpContext.Current; // 原有逻辑保持不变 public User LoggedInUser => ... // 原有逻辑保持不变 public Collection<SiteWideSettings> SiteWideSettings => ... }
3. 依赖注入注册
你需要在项目的DI容器中注册IMyCustomContext的单例实例,因为原类本身是单例设计,直接用工厂方法返回原有单例即可,示例(以Microsoft.Extensions.DependencyInjection为例,其他容器逻辑类似):
// 注册接口对应单例实例 services.AddSingleton<IMyCustomContext>(_ => MyCustomContext.Current);
注册完成后,你期望的MyService注入写法就可以正常运行了。
关于成员是否需要转方法的问题
不需要特意转换为方法,保留属性即可,原因如下:
- 依赖注入对属性和方法没有特殊适配要求,只要接口定义和实现匹配即可正常工作
- 你现有几个成员都是轻量的状态获取逻辑,无输入参数,完全符合C#属性的使用场景
- 只有当后续逻辑需要新增输入参数、或者包含重IO/异步逻辑时,再改为方法即可
内容的提问来源于stack exchange,提问作者Raghav
相关产品推荐
相关产品推荐

