Кэширование не существует в пространстве имен Microsoft.Extensions - PullRequest
0 голосов
/ 06 сентября 2018

Я перемещаю некоторую логику из микросервиса в функцию лазури.

Дела идут довольно гладко, однако я столкнулся с проблемой зависимости. У меня были некоторые функции кэширования в микросервисе, которые я хотел бы сохранить в функции azure, однако проект функции не будет создан, поскольку он не может разрешить Microsoft.Extensions.Caching.Memory пространство имен.

Я установил Microsoft.Extensions.DependencyInjection через nuget в новом проекте функции, чтобы я мог использовать DI в этом приложении функции. Я думаю, что это причина, по которой Microsoft.Extensions.Caching больше не разрешается.

Ошибка является общей: The type or namespace 'Caching' does not exist in the namespace 'Microsoft.Extensions'

Разве они оба не должны отображаться в пространстве имен Microsoft.Extensions? У кого-нибудь есть идеи, как решить эту проблему?

Спасибо

РЕДАКТИРОВАТЬ: Некоторые примеры кода.

Код функции: (Настройка DI почти точно это )

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using PI.Warehouses.API.Repositories;
using ESPIWarehouseFunction.Injection;

namespace ESPIWarehouseFunction
{
    public static class WarehouseFunctions
    {

        [FunctionName("GetAll")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequest req, 
            TraceWriter log, [Inject(typeof(IWarehouseStateRepository))]IWarehouseStateRepository repoW)
        {
            log.Info("GetAll Function is processing a request");
            var warehouses = repoW.GetAllWarehouses();
            return warehouses != null ? 
                (ActionResult)new OkObjectResult(warehouses) :
                new BadRequestObjectResult("Something went wrong with this request");
        }
    }
}

Один из множества кусков кода, который использует кеш:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using MediatR;
using PI.Warehouses.Domain.Aggregate.Commands;
using PI.Warehouses.Domain.Aggregate.Events;
using PI.Warehouses.Domain.Model;
using PI.Warehouses.API.Repositories;
using Newtonsoft.Json;
using PI.Warehouses.Domain.Aggregate.Exceptions;
using Microsoft.Extensions.Caching.Memory;

namespace PI.Warehouses.API.Application.Handlers.Commands
{
    public class AddMaterialHandler : IRequestHandler<AddMaterialCommand, EventList>
    {
        private readonly IEventRepository _repoEvents;
        private readonly IWarehouseStateRepository _repoWarehouse;
        private readonly IMediator _mediator;
        private IMemoryCache _cache;
        private EventList _eventsCreated;

        public AddMaterialHandler(IEventRepository repoE, IWarehouseStateRepository repoW, IMediator mediator, IMemoryCache cache)
        {
            _repoEvents = repoE;
            _repoWarehouse = repoW;
            _mediator = mediator;
            _cache = cache;
            _eventsCreated = new EventList();
        }

            // some setups stuffs ...

            WarehouseState state;
            if (!_cache.TryGetValue(cmd.WarehouseId, out WarehouseState cachedState))
                state = await _repoWarehouse.GetWarehouseState(cmd.WarehouseId);
            else
                state = new WarehouseState(cachedState);


            // Rest of this handler
    }
}

1 Ответ

0 голосов
/ 06 сентября 2018

Я только что создал чистую функцию и установил оба пакета, я использовал интерфейсы от них обоих (поэтому у меня есть оба использования), и все, кажется, работает правильно:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

        public class MyCache : IMemoryCache
        {
            public void Dispose()
            {
                throw new System.NotImplementedException();
            }

            public bool TryGetValue(object key, out object value)
            {
                throw new System.NotImplementedException();
            }

            public ICacheEntry CreateEntry(object key)
            {
                throw new System.NotImplementedException();
            }

            public void Remove(object key)
            {
                throw new System.NotImplementedException();
            }
        }

        public class ServicesCollection : IServiceCollection
        {
            public IEnumerator<ServiceDescriptor> GetEnumerator()
            {
                throw new System.NotImplementedException();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            public void Add(ServiceDescriptor item)
            {
                throw new System.NotImplementedException();
            }

            public void Clear()
            {
                throw new System.NotImplementedException();
            }

            public bool Contains(ServiceDescriptor item)
            {
                throw new System.NotImplementedException();
            }

            public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
            {
                throw new System.NotImplementedException();
            }

            public bool Remove(ServiceDescriptor item)
            {
                throw new System.NotImplementedException();
            }

            public int Count { get; }
            public bool IsReadOnly { get; }
            public int IndexOf(ServiceDescriptor item)
            {
                throw new System.NotImplementedException();
            }

            public void Insert(int index, ServiceDescriptor item)
            {
                throw new System.NotImplementedException();
            }

            public void RemoveAt(int index)
            {
                throw new System.NotImplementedException();
            }

            public ServiceDescriptor this[int index]
            {
                get => throw new System.NotImplementedException();
                set => throw new System.NotImplementedException();
            }
        }
    }
}

Без примера из вашего кода будет трудно диагностировать реальную проблему.

EDIT: Вот мой .csproj для проекта:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.1.2" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.14" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>
...