繁体   English   中英

将依赖注入应用于抽象类C#的不同实现

[英]Applying Dependency Injection to different implementations of an abstract class c#

当我可以在控制器中注入2个抽象类的不同实现时,我想在.net核心应用程序中构建MVC方案。 这些实现调用其外部相对API。 也许架构是错误的,因此我向您提出建议,但请先跟随我思考。 我创建一个通用的抽象类。 为什么要抽象? 因为每个人调用API的基本方式/属性都是相同的。 就我而言,到目前为止,我只有一个HttpClient。

public abstract class ApiCaller
{
    protected static HttpClient client;
    protected static string ApiUrl;

    public ApiCaller(string apiUrl)
    {
        client = new HttpClient();
        ApiUrl = apiUrl;
    }

    public abstract string GetApiResultAsync();
}

之后,我将拥有两个不同的类Api1ServiceApi2Service ,它们扩展了ApiCaller并将具有它们自己的不同方式来调用其相对API。

public class Api1Service : ApiCaller
{
    public Api1Service(string apiUrl) : base(apiUrl)
    {

    }

    public override string GetApiResultAsync()
    {
        ...
    }
}


public class Api2Service : ApiCaller
{
    public Api2Service(string apiUrl) : base(apiUrl)
    {

    }

    public override string GetApiResultAsync()
    {
        ...
    }
}

现在,由于要使用两种业务服务,因此我想在控制器中同时注入两种方式。但是我不知道这是否可行。

[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    private readonly ApiCaller _apiCaller;

    public BooksAndAlbumsController(ApiCaller apiCaller)
    {
        _apiCaller = apiCaller;
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
        _apiCaller.GetApiResultAsync() //but I want to use both my apiCallers
    }
}

因此,无论如何,我需要在我的容器中注册我的抽象类的两个实现。 我该如何实现? 如果您发现我的架构存在缺陷,请告诉我!

您可以注入IEnumerable<ApiCaller> ,然后同时使用它们。

在容器中注册两个ApiCaller,然后将IEnumerable<ApiCaller>注入到控制器中。

像这样:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ApiCaller, Api1Service>();
    services.AddSingleton<ApiCaller, Api2Service>();
}

我的控制器

[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    private readonly IEnumerable<ApiCaller> _apiCallers;

    public MyController(IEnumerable<ApiCaller> apiCallers)
    {
        _apiCallers = apiCallers;
    }

    [HttpPost]
    public async Task Post([FromBody] string value)
    {
        // Loop through one by one or call them in parallel, up to you.
        foreach(var apiCaller in _apiCallers)
        {
            var result = await apiCaller.GetApiResultAsync();
        }
    }
}

另一种可能性是注册Api1Service和Api2Service,然后像这样注入它们。 但是,它不会像第一个解决方案那样动态/灵活。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<Api1Service>();
    services.AddSingleton<Api2Service>();
}

我的控制器

[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    private readonly Api1Service _api1Service;
    private readonly Api2Service _api2Service;

    public MyController(Api1Service api1Service, Api2Service api2Service)
    {
        _api1Service = api1Service;
        _api2Service = api2Service;
    }

    [HttpPost]
    public async Task Post([FromBody] string value)
    {
        var result1 = await apiService1.GetApiResultAsync();
        var result2 = await apiService2.GetApiResultAsync();
    }
}

检查有关复合模式

public sealed class CompositeApiCaller : ApiCaller
{
    private const string SEPARATION_STRING = Environnement.NewLine;

    private ApiCaller[] _apiCallers;

    public CompositeApiCaller(params ApiCaller[] apiCallers)
    {
        _apiCallers = apiCallers;
    }

    public override string GetApiResultAsync()
    {
        var builder = new StringBuilder();

        for (int i = 0; i < _apiCallers.Length; i++)
        {
            if (i > 0)
                builder.Append(SEPARATION_STRING);

            builder.Append(apiCaller.GetApiResultAsync());
        }

        return builder.ToString();
    }
}

您可以使用NamedHttpClients和工厂

public static class NamedHttpClients {
  public const string StarTrekApi = "StarTrekApi";
  public const string StarWarsApi = "StarWarsApi";
}


services.AddHttpClient(NamedHttpClients.StarTrekApi, client => {
    client.BaseAddress = new Uri("http://stapi.co/api/v1/rest");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("apiClientTest", "1.0"));
});

services.AddHttpClient(NamedHttpClients.StarWarsApi, client => {
  client.BaseAddress = new Uri("https://swapi.co/api/");
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("apiClientTest", "1.0"));
});

然后创建一个工厂,将其注入控制器

public interface IFanApiClientFactory {
  IFanApiClient CreateStarWarsApiClient();
  IFanApiClient CreateStarTrekApiClient();
}

public class FanApiClientFactory : IFanApiClientFactory {
  private readonly IHttpClientFactory _httpClientFactory;

  public FanApiClientFactory(IHttpClientFactory httpClientFactory) {
    _httpClientFactory = httpClientFactory;
  }

  public IFanApiClient CreateStarWarsApiClient() {
    var client = _httpClientFactory.CreateClient(NamedHttpClients.StarWarsApi);
    return new StarWarsApiClient(client);
  }

  public IFanApiClient CreateStarTrekApiClient() {
    var client = _httpClientFactory.CreateClient(NamedHttpClients.StarTrekApi);
    return new StarTrekApiClient(client);
  }
}

注册工厂

services.AddSingleton<IFanApiClientFactory, FanApiClientFactory>();

至少实现具体的api客户端

public class StarWarsApiClient : IFanApiClient {
  private readonly HttpClient _client;

  public StarWarsApiClient(HttpClient client) {
    _client = client;
  }

  public async Task<string> GetMostImportantPerson() {
    var response = await _client.GetAsync("people/1");
    return await response.Content.ReadAsStringAsync();
  }
}


public class StarTrekApiClient : IFanApiClient {

  private readonly HttpClient _client;

  public StarTrekApiClient(HttpClient client) {
    _client = client;
  }

  public async Task<string> GetMostImportantPerson() {
    var response = await _client.GetAsync("character/CHMA0000126904");
    return await response.Content.ReadAsStringAsync();
  }
}

最后是控制器

public class HomeController : Controller {

  private readonly IFanApiClientFactory _fanApiClientFactory;

  public HomeController(IFanApiClientFactory fanApiClientFactory) {
    _fanApiClientFactory = fanApiClientFactory;
  }

  public async Task<IActionResult> Index() {

    var starWarsApiClient = _fanApiClientFactory.CreateStarWarsApiClient();
    var starTrekApiClient = _fanApiClientFactory.CreateStarTrekApiClient();

    var person1 = await starTrekApiClient.GetMostImportantPerson();
    var person2 = await starWarsApiClient.GetMostImportantPerson();

    return View();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM