Елементите не са в кеша след добавянето му. използване на Web API и кеша на паметта

Когато добавя елементи към кеша на паметта, той е празен при следващата заявка. Може ли някой да ми помогне, моля?

Ето моята кеш услуга:

    public class CacheService : ICacheService
{
    private readonly ObjectCache _cache;

    public CacheService(ObjectCache cache)
    {
        _cache = cache;
    }

    public virtual void Add(object item, string key, int cacheTime, ExpirationInterval expirationInterval = ExpirationInterval.Hours)
    {
        if (item == null)
            return;
        var cachePolicy = new CacheItemPolicy();
        switch (expirationInterval)
        {
            case ExpirationInterval.Minutes:
                cachePolicy.SlidingExpiration = new TimeSpan(0, cacheTime, 0);
                break;
            case ExpirationInterval.Hours:
                cachePolicy.AbsoluteExpiration = DateTime.Now.AddHours(cacheTime);
                break;
            case ExpirationInterval.Infinite:
                cachePolicy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
                break;
            default:
                throw new ArgumentOutOfRangeException("expirationInterval");
        }
        _cache.Add(key, item, cachePolicy);
    }

    public bool Exists(string key)
    {
        return _cache[key] != null;
    }

    public T Get<T>(string key)
    {

        return (T)_cache[key];
    }

Регистрирайте моята услуга с ninject тук:

            kernel.Bind<System.Runtime.Caching.ObjectCache>()
            .To<System.Runtime.Caching.MemoryCache>()
            .InSingletonScope()
            .WithConstructorArgument("name", "Enquiries")
            .WithConstructorArgument("config", (object) null);

След това използвам кеш услугата по-долу в услуга за запитвания:

  public class EnquiriesService : IEnquiriesService
{
    private readonly ICacheService _cacheService;
    private readonly IUnitOfWork _unitOfWork;

    public EnquiriesService(ICacheService cacheService, IUnitOfWork unitOfWork)
    {
        _cacheService = cacheService;
        _unitOfWork = unitOfWork;
    }

    public IEnumerable<Enquiry> GetEnquiries(DateTime date)
    {
        var cacheName = "Enquires_" + date.ToShortDateString();
        IEnumerable<Enquiry> enquiries;

        if (_cacheService.Exists(cacheName))
        {
            enquiries = _cacheService.Get<IEnumerable<Enquiry>>(cacheName);
        }
        else
        {
            enquiries =
                _unitOfWork.EnquiriesRepository.GetAll()
                    .Where(x => DbFunctions.TruncateTime(x.DateOfEnquiry) == date.Date);
            _cacheService.Add(enquiries, cacheName, 24);
        }
        return enquiries;
    }

след това тази услуга се инжектира в моя контролер:

        public EnquiriesController(IEnquiriesService enquiriesService)
    {
        _enquiriesService = enquiriesService;
    }

    [HttpGet]
    public IEnumerable<Enquiry> Enquiries(DateTime date)
    {
        return _enquiriesService.GetEnquiries(date);
    }

Някакви идеи защо мога да видя, че елементите са добавени успешно, но когато се опитам да ги извлека втори път, няма нищо в кеша? Предполагам, че кеша на паметта се инстанцира при всяка заявка? Как мога да спра това и да позволя на моя кеш обект да продължи да съществува?


person Jonny C    schedule 08.08.2014    source източник


Отговори (1)


Изглежда, че е бъги:

Stackoverflow: Обвързването на Singleton Scope не работи по предназначение
Stackoverflow: Ninject InSingletonScope с Web Api RC

И двете публикации са стари, но изглежда, че срещате едни и същи проблеми. Може би трябва да използвате този подход вместо това:

kernel.Bind<System.Runtime.Caching.ObjectCache>()
        .To<System.Runtime.Caching.MemoryCache>()
        .ToConstant(new MemoryCache("Enquiries"));

или просто

 kernel.Bind<System.Runtime.Caching.ObjectCache>()
        .To<System.Runtime.Caching.MemoryCache>()
        .ToConstant(MemoryCache.Default);
person Stefan Ossendorf    schedule 20.11.2014