Unity容器:如何正确解析已注册为单例的带参MemoryCache
解决Unity容器注入IMemoryCache的构造函数选择失败问题
问题出在你直接传递MemoryCacheOptions实例,但MemoryCache的构造函数需要的是IOptions<MemoryCacheOptions>类型参数——MemoryCacheOptions本身并没有实现IOptions<MemoryCacheOptions>接口,这个接口的标准实现是OptionsWrapper<T>,你需要用它来包装配置对象。
正确的注册和解析步骤如下:
1. 注册IOptions<MemoryCacheOptions>实例
先创建配置好的MemoryCacheOptions,再用OptionsWrapper<MemoryCacheOptions>包装后注册到Unity容器:
var cacheOptions = new MemoryCacheOptions { SizeLimit = 2, TrackStatistics = true }; // 注册IOptions<MemoryCacheOptions>的单例实例 container.RegisterInstance<IOptions<MemoryCacheOptions>>(new OptionsWrapper<MemoryCacheOptions>(cacheOptions));
2. 注册IMemoryCache到MemoryCache
接着注册IMemoryCache的实现,使用容器控制生命周期(单例):
container.RegisterType<IMemoryCache, MemoryCache>(new ContainerControlledLifetimeManager());
3. 正常解析或注入
现在可以直接解析IMemoryCache,或者在类的构造函数中注入,Unity会自动处理依赖:
// 直接解析 var cache = container.Resolve<IMemoryCache>(); // 在业务类中注入使用 public class ClassManager { private readonly IMemoryCache _memoryCache; public ClassManager(IMemoryCache memoryCache) { _memoryCache = memoryCache; } }
报错原因说明
你之前用ParameterOverride传递MemoryCacheOptions,但Unity找不到匹配IOptions<MemoryCacheOptions>的构造参数,因此抛出构造函数选择失败的异常。MemoryCache的构造函数签名是:
public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor)
必须传入IOptions<MemoryCacheOptions>类型的实例,而非MemoryCacheOptions本身。用OptionsWrapper<T>包装后,就能满足构造函数的参数类型要求,Unity即可正确解析。
内容的提问来源于stack exchange,提问作者user3613025
相关产品推荐
相关产品推荐

