首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >作用域服务中的IMemoryCache

作用域服务中的IMemoryCache
EN

Stack Overflow用户
提问于 2021-09-20 20:50:14
回答 1查看 1.1K关注 0票数 0

我有一个作用域服务,我希望将IMemoryCache注入其中。

在启动过程中使用以下代码添加了IMemoryCache:

代码语言:javascript
复制
services.AddMemoryCache();
services.AddScoped<IUserService, UserService>();

Autofac在Program.cs中配置如下:

代码语言:javascript
复制
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

有没有人对此有任何建议?

EN

回答 1

Stack Overflow用户

发布于 2021-09-21 07:26:24

这对我适用于Autofac:

代码语言:javascript
复制
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注册为SingleInstanceIOptions<>,因为MemoryCache依赖于它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69260663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档