使用内存缓存时,Asp.Net MVC中的InvalidOperationException

时间:2018-12-15 10:22:38

标签: c# asp.net-mvc caching

我需要使用.NetFramework 4.5.2在我的网站上应用Microsoft.Extensions.Caching.Memory version 1.1.2,但出现此异常:

  

Unity.Exceptions.ResolutionFailedException:'解决   依赖项失败,类型=   'Tranship.UI.Areas.Portal.Controllers.SearchResultController',名称=   '(没有)'。发生以下异常:正在解决。例外是:   InvalidOperationException-当前类型,   Microsoft.Extensions.Caching.Memory.IMemoryCache是​​一个接口,   无法构建。您是否缺少类型映射?

我正在使用Asp.net MVC(不是Core)并使用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; } } } 这是我的CS文件:

v-model

2 个答案:

答案 0 :(得分:6)

您需要将IMemoryCache注册到Unity容器

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

UnityContainer container = new UnityContainer(); // your unity container

MemoryCacheOptions memoryCacheOptions = new MemoryCacheOptions
{
    //config your cache here
};

MemoryCache memoryCache = new MemoryCache(Options.Create<MemoryCacheOptions>(memoryCacheOptions));
container.RegisterInstance<IMemoryCache>(memoryCache);

答案 1 :(得分:-1)

为了能够在.net核心中使用基于.net 4.5.2的现有缓存实现,我已将其移植为使用 System.Runtime缓存而不是System Web。就像魅力一样。

Here's official documentation