我有一个作用域服务,我希望将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,但我也尝试过关闭它,并得到了相同的结果:
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder‘在'Rostering.Infrastructure.Identity.Services.UserService’类型上找到的任何构造函数都不能用可用的服务和参数调用:无法解析构造函数‘'Microsoft.Extensions.Caching.Memory.IMemoryCache .ctor(Microsoft.AspNetCore.Http.IHttpContextAccessor,Microsoft.Extensions.Caching.Memory.IMemoryCache)'.’的参数‘Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache
有没有人对此有任何建议?
发布于 2021-09-21 07:26:24
这对我适用于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依赖于它。
https://stackoverflow.com/questions/69260663
复制相似问题