V2Listener не найдена ошибка - PullRequest
0 голосов
/ 27 мая 2018

Я подключаю службу веб-API к службе без сохранения состояния.

Backservice называется MyProject.Management.Company, а ее код:

internal sealed class Company: StatelessService,ICompanyManagement
{
    private readonly CompanyManagementImpl _impl;

    public Tenents(StatelessServiceContext context, CompanyManagementImpl impl)
        : base(context)
    {
        this._impl = impl;
    }



    /// <summary>
    /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
    /// </summary>
    /// <returns>A collection of listeners.</returns>
    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new[]
        {
            new ServiceInstanceListener(serviceContext => new FabricTransportServiceRemotingListener(serviceContext, this), "ServiceEndpoint")
        };
    }

    /// <summary>
    /// This is the main entry point for your service instance.
    /// </summary>
    /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        // TODO: Replace the following sample code with your own logic 
        //       or remove this RunAsync override if it's not needed in your service.

        long iterations = 0;

        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);

            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
        }
    }

    public Task CreateCompany(Company company)
    {
        return _impl.CreateCompany(company);
    }
    public Task<List<Company>> GetAllCompanies()
    {
        return _impl.GetAllCompanies();
    }

    public Task<Company> GetCompanyById(string companyId)
    {
        return _impl.GetCompanyById(companyId);
    }
}

Код - слушатель.Код взят из Это сообщение в блоге , и даже код документации не компилируется Документация Метод CreateServiceRemotingListenervextension не существует.

ICompanyManagement является интерфейсом, наследуемым отИнтерфейс IService и его реализация реализуются через CompanyManagament, который на этом этапе просто возвращает статические объекты.

API называется MyProject.Portal , а код контроллера:

public class CompanyController : Controller
    {
        ICompanyManagement _proxy;
        public CompanyController(StatelessServiceContext context)
        {
            string serviceUri = $"{context.CodePackageActivationContext.ApplicationName}" + "/MyProject.Management.Company";


            _proxy = ServiceProxy.Create<ICompanyManagement>(new Uri(serviceUri));


        }

        // GET: api/Company
        [HttpGet]
        public async Task<JsonResult> Get()
        {
            try
            {
                var result = await _proxy.GetAllCompanies();

                return this.Json(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

При выполнении кода возвращается следующая ошибка.

NamedEndpoint 'V2Listener' не найден в адресе '{"Конечные точки": {"ServiceEndpoint": "localhost: 59286 + 12a705ed-11a5-4bf5-bafd-84179c966257-131719261525940414-9e876439-9294-4ec9-8b33-05f17515aaf4 "}} 'для раздела' 12a705ed-11a5-4bf5-bafd-84179c966257 '

Наконец: я использую .netcore v2, сервисная фабрика v6.2.274.

1 Ответ

0 голосов
/ 28 мая 2018

Сразу после использования в файле ICompanyManagement добавьте следующую строку:

[assembly: FabricTransportServiceRemotingProvider(RemotingListener = RemotingListener.V2Listener, RemotingClient = RemotingClient.V2Client)]

В манифесте вашей службы (CompanyManagement) (файл ServiceManifest.xml) убедитесь, что конечная точкаустановлена ​​на версию 2:

<Resources>
    <Endpoints>
        <Endpoint Name="ServiceEndpointV2" />  
    </Endpoints>
</Resources>

Измените метод CreateServiceInstanceListeners на:

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    return this.CreateServiceRemotingInstanceListeners();
}

Наконец, в вашем контроллере веб-API зарегистрируйте прокси-сервер службы следующим образом:

ICompanyManagement companyManagementClient = ServiceProxy.Create<ICompanyManagement>(new Uri($"fabric:/{applicationName}/{serviceName}"));

Если вы выполните эти шаги, это сработает.

...