【发布时间】:2019-05-16 09:59:42
【问题描述】:
我需要在我的网站上使用.NetFramework 4.5.2 申请In-Memory Cache,但我得到了这个例外:
Unity.Exceptions.ResolutionFailedException: '解决 依赖失败,类型 = 'Tranship.UI.Areas.Portal.Controllers.SearchResultController',名称 = '(没有)'。异常发生时:解决时。例外是: InvalidOperationException - 当前类型, Microsoft.Extensions.Caching.Memory.IMemoryCache,是一个接口和 无法构建。您是否缺少类型映射?
我正在使用 Asp.net MVC(不是 Core)并使用 Microsoft.Extensions.Caching.Memory version 1.1.2
这是我的cs文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tranship.Business.Core;
using Tranship.Business.Interface;
using Tranship.DataAccess.UnitOfWork;
using Tranship.Domain.Context;
using Tranship.Domain.Model;
using Tranship.DomainService.Interface;
using Tranship.ViewModel.Model;
using Tranship.ViewModel.Mapper;
using Tranship.ViewModel.Parameter;
using Microsoft.Extensions.Caching.Memory;
namespace Tranship.DomainService.Core
{
public class ScheduleDomainService : IScheduleDomainService
{
private readonly IMemoryCache MemoryCache;
private readonly string key = "TranshipMemoryCache";
public BoundedContextUnitOfWork Context { get; set; }
public IScheduleBiz ScheduleBiz { get; set; }
public ScheduleDomainService(IMemoryCache memoryCache)
{
Context = new BoundedContextUnitOfWork(new BoundedContext());
ScheduleBiz = new ScheduleBiz(Context);
MemoryCache = memoryCache;
}
public List<ScheduleViewModel> GetScheduleBySearchParameter(SearchTripParameters parameters)
{
DateTime from;
DateTime to;
List<ScheduleViewModel> cacheObject = new List<ScheduleViewModel>();
if (!MemoryCache.TryGetValue(key, out cacheObject))
{
// Cache is empty or timespan has been terminated
cacheObject = ScheduleBiz.GetAll();
MemoryCache.Set(key, cacheObject, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1)));
}
else
{
// Cache is full
cacheObject = MemoryCache.Get(key) as List<ScheduleViewModel>;
}
return cacheObject;
}
}
}
【问题讨论】:
-
只是猜测:Unity 无法解析 IMemoryCache。可能缺少 ÌMemoryCache` 实现的注册。
-
你确定你在启动时在 ConfigureServices 上添加了 AddMemoryCache() 检查这个docs.microsoft.com/en-us/aspnet/core/performance/caching/…
-
@Ahmed Ghoniem AddMemoryCache() 属于 .net 核心。我正在使用 Asp.Net MVC。
-
如果我添加 container.RegisterType
();注册它说 MemoryCacheOptions 注册丢失
标签: c# asp.net-mvc asp.net-core caching memorycache