首页 > 解决方案 > 使用带有接口的 OpenApi 客户端 .NET Core

问题描述

外面的人一定已经遇到过这种情况......

我创建了一个 WebApi 解决方案,实现了招摇,完整的文档,整个 9 码!

现在,我想将此 Api 作为我的 Web 应用程序上的连接服务使用。因此,请遵循在线的每个教程:

这会在我的解决方案中生成一个部分类(MyTestApiClient)

public parial class MyTestApiClient
{
   // auto generated code
}

下一步,在 Startup.cs 中注入服务

services.AddTransient(x =>
{
   var client = new MyTestApiClient("https://localhost:5001", new HttpClient());
   return client;
});

然后,将该类注入到某个被消耗的类中,这一切都有效

public class TestService
{
    private readonly MyTestApiClient _client; // this is class, not an interface -> my problem
    public TestService(MyTestApiClient client)
    {
        _client = client;
    }

    public async Task<int> GetCountAsync()
    {
        return _client.GetCountAsync();
    }
}

所以到目前为止一切都有效。但是,这个生成的 OpenApi 客户端没有用于 DI 和单元测试的接口。

我通过创建一个本地接口 IMyTestApiClient 来解决这个问题,并将其添加到生成的类 (MyTestApiClient) 中。我的 WebApi 中只有 1 个端点,所以必须在我的界面上声明它。

public parial class MyTestApiClient : IMyTestApiClient
{
   // auto generated code
}
public interface IMyTestApiClient
{
   // implemented in generated MyTestApiClient class
   Task<int> GetCountAsync();
}
services.AddTransient<IMyTestApiClient, MyTestApiClient>(x =>
{
   IMyTestApiClient client = new MyTestApiClient("https://localhost:5001", new HttpClient());
   return client;
});
public class TestService
{
    private readonly IMyTestApiClient _client; // now injecting local interface instead of the generated class - great success
    public TestService(IMyTestApiClient client)
    {
        _client = client;
    }

    public async Task<int> GetCountAsync()
    {
        return _client.GetCountAsync();
    }
}

但这是一个不好的方法,因为它让我手动创建一个接口并显式声明我想要使用的方法。此外,每次我的 Api 更新时,我都必须调整我的本地界面。

所以提问时间: 如何添加自动生成接口的 OpenApi 服务参考?提前感谢您提供任何帮助以找到可行的解决方案。

标签: .net-coredependency-injectionswaggeropenapiopenapi-generator

解决方案


您可能已经找到了答案,但我遇到了同样的问题,并通过在我的 .csproj 中的 OpenAPI 参考的选项部分添加 /GenerateClientInterfaces:true 来解决它:

<OpenApiReference Include="api.json" CodeGenerator="NSwagCSharp" Namespace="MyNamespace" ClassName="MyClassName">
    <SourceUri>https://localhost:7040/swagger/v1/swagger.json</SourceUri>
    <OutputPath>MyClient.cs</OutputPath>
    <Options>/GenerateClientInterfaces:true</Options>
</OpenApiReference>

推荐阅读