C#构造函数依赖注入:运行时传入参数可行吗?
解决方案
首先修正你配置注册里的笔误:第三个Configure调用的第一个参数应该是ProfileCacheOptions.Key3,而非重复的Key2:
services.Configure<ProfileCacheOptions>( ProfileCacheOptions.Key3, config.GetSection(ProfileCacheOptions.Key3));
你之前直接传字符串到AddSingleton的方式行不通,因为这种重载无法自动注入IMemoryCache和IOptionsSnapshot这类框架管理的依赖。正确做法是使用工厂方法注册服务,在工厂里手动组合所有构造参数:
// 注册第一个实例 services.AddSingleton<ICachedDataSource<Class1>>(sp => new MemoryCacheData<Class1>( sp.GetRequiredService<IMemoryCache>(), sp.GetRequiredService<IOptionsSnapshot<ProfileCacheOptions>>(), ProfileCacheOptions.Key1)); // 注册第二个实例 services.AddSingleton<ICachedDataSource<Class2>>(sp => new MemoryCacheData<Class2>( sp.GetRequiredService<IMemoryCache>(), sp.GetRequiredService<IOptionsSnapshot<ProfileCacheOptions>>(), ProfileCacheOptions.Key2)); // 注册第三个实例 services.AddSingleton<ICachedDataSource<Class3>>(sp => new MemoryCacheData<Class3>( sp.GetRequiredService<IMemoryCache>(), sp.GetRequiredService<IOptionsSnapshot<ProfileCacheOptions>>(), ProfileCacheOptions.Key3));
同时确保MemoryCacheData的构造函数参数类型匹配(注意你示例里的CachedDataBaseClassOptions要和配置的ProfileCacheOptions类型一致,或保证基类兼容):
public class MemoryCacheData<T> : ICachedDataSource<T> { private readonly ProfileCacheOptions _options; private readonly IMemoryCache _cache; public MemoryCacheData( IMemoryCache cache, IOptionsSnapshot<ProfileCacheOptions> options, string configKey) { _cache = cache; _options = options.Get(configKey); } // 实现ICachedDataSource<T>的业务方法 }
这种方式的核心是借助服务提供者(IServiceProvider)获取框架托管的依赖,再手动传入指定的配置Key,就能创建多个逻辑一致但配置不同的单例实例。
内容的提问来源于stack exchange,提问作者Tom Lee
相关产品推荐
相关产品推荐

