首页 > 解决方案 > 范围服务中的 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)'。

有人对为什么会这样有任何建议吗?

标签: c#.net-coredependency-injectionautofac

解决方案


这对我来说适用于 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>();
    }
}

我已经注册IMemoryCacheSingleInstance并且IOptions<>因为MemoryCache依赖于它。


推荐阅读