c# - 无法从 ViewComponent 中解析缓存服务

标签 c# dependency-injection .net-core razor-pages memorycache

我在 Startup.cs 中注册缓存服务如下:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMemoryCache();            
        services.AddTransient<DataFacade, DataFacade>();
        ...
    }

在同一个项目中,我的 _Layout.cshtml header 包含一个 ViewComponent

@await Component.InvokeAsync(nameof(ViewComponents.PageHeader))

这会调用 ModelBuilder 组件并具有如下构造函数:

using MyApp.Services;
using MyApp.Website.ModelBuilder;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;

namespace MyApp.Website.ViewComponents
{
    [ViewComponent]
    public class Header : ViewComponent
    {
        private readonly HeaderModelBuilder _modelBuilder;

        public Header(HeaderModelBuilder modelBuilder)
        {
            _modelBuilder = modelBuilder;
        }

...并且 ModelBuilder 服务引用了 DataFacade 服务:

using MyApp.Data.ExternalCountryData;
using MyApp.Services;
using MyApp.Website.Constants;
using MyApp.Website.Models;

namespace MyApp.Website.ModelBuilder
{
    public class HeaderModelBuilder
    {
        private readonly DataFacade _dataFacade;

        public HeaderModelBuilder(DataFacade dataFacade)
        {
            _dataFacade = dataFacade;
        }

...它有一个构造函数如下:

using System;
using MyApp.Data;
using MyApp.Data.ExternalSiteData;
using MyApp.Domain.Services.Data;
using Microsoft.Extensions.Caching.Memory;

namespace MyApp.Services
{
    public class DataFacade
    {
        private MemoryCache _cache;
        public DataFacade(MemoryCache memoryCache)
        {
            _cache = memoryCache;
        }

但是,在运行代码时,Program.cs 抛出以下内容:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.MemoryCache' while attempting to activate 'MyApp.Services.DataFacade'.

如果我注释掉 View 组件,应用程序的其他部分可以正常访问缓存。

为什么 View 组件会出现问题?我是否错误地注册了其中一项服务?

最佳答案

注入(inject) IMemoryCache 抽象而不是实现

public class DataFacade {
    private readonly IMemoryCache _cache;

    public DataFacade(IMemoryCache memoryCache) {
        _cache = memoryCache;
    }

    //...

引用Use IMemoryCache

添加内存缓存的源码添加服务集合注册时的接口(interface)

/// <summary>
/// Adds a non distributed in memory implementation of <see cref="IMemoryCache"/> to the
/// <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddMemoryCache(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddOptions();
    services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());

    return services;
}

Source

关于c# - 无法从 ViewComponent 中解析缓存服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58375098/

相关文章:

c# - Python 中 C# 的 GetEncoding ("28591") 相当于什么?

c# - 转置非方阵 C#

c# - 如何在 ASP.NET 5 中动态创建和注入(inject)服务?

dependency-injection - unity InjectionConstructor 传递对象数组

java - HK2中如何将多个接口(interface)收集到一个Collection中?

c# - AddMicrosoftIdentityWebApp 与 AddAzureADBearer

docker - 如何在 Kubernetes 内部调用 Redis?删除旧 Redis 服务的问题

c# - "System.ServiceModel.Primitives"- 找不到程序集或找不到依赖项

c# - 如何解决 'Invalid initializer member declarator' 错误 C#,从 CSV 文件读取

c# - 如何将 json-patch 应用于 .net core 中的纯 json?