c# - 范围服务中的 IMemoryCache
问题描述
我有一个范围服务,我希望将 IMemoryCache 注入其中。
IMemoryCache 已在启动期间使用以下代码添加:
services.AddMemoryCache();
services.AddScoped<IUserService, UserService>();
Autofac 在 Program.cs 中配置如下:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
我有另一个类,UserService,我想用它访问缓存的数据,但我遇到了 DI 问题。我应该添加我正在使用 AutoFac,但也尝试将其关闭并获得相同的结果:
无法使用可用的服务和参数调用类型为“Rostering.Infrastructure.Identity.Services.UserService”的“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”的构造函数:无法解析参数“Microsoft.Extensions.Caching。 Memory.IMemoryCache memoryCache' 的构造函数'Void .ctor(Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.Extensions.Caching.Memory.IMemoryCache)'。
有人对为什么会这样有任何建议吗?
解决方案
这对我来说适用于 Autofac:
public interface IUserService
{
}
public class UserService : IUserService
{
public UserService(IMemoryCache memoryCache)
{
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// autofac container builder
var builder = new ContainerBuilder();
builder.RegisterType<MemoryCache>().As<IMemoryCache>().SingleInstance();
builder.RegisterType<UserService>().As<IUserService>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptions<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptionsSnapshot<>)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(OptionsMonitor<>)).As(typeof(IOptionsMonitor<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>));
builder.RegisterGeneric(typeof(OptionsCache<>)).As(typeof(IOptionsMonitorCache<>)).SingleInstance();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var us = scope.Resolve<IUserService>();
}
}
我已经注册IMemoryCache
为SingleInstance
并且IOptions<>
因为MemoryCache
依赖于它。
推荐阅读
- python - 从python中的命令行传递参数
- php - 通过 AWS SES 发送日历邀请 - 错误:重复标头“内容类型”
- css - 从线向上滑动动画
- python - 试图在 usecols Pandas 中传递用户输入
- compiler-construction - 如何找到yacc规则的字符串?
- python - Python - 如果条件为 FALSE,则移至下一个列表元素
- python-3.x - 从整数列表中找到偶数的和
- javascript - 无法使用 jQuery 编辑、更新和取消表格单元格文本
- vagrant - 具有多集群的 Vagrantfile 设置
- python - 如何使用 python 将 LineString 中的多个点从 JSON 添加到 GeoJSON?