How to get a GitHub repository using Octokit C#

1.8k Views Asked by At

I'm trying to integrate GitHubAPI in a web app that I am developing. I heard that the best way to do this in C# is using Octokit library but I can't find a very explicit documentation. Now, first of all I am trying to get a repo from GitHub. When I started, I manually accessed the endpoints as shown in the GitHub API. However, it seems that doing a commit that way is not possible so I switched to Octokit but I have some problems here.

Here is my OctokitGitService class:

*imports here*


namespace Web.Git.Api.Services;

public class OctokitGithubClient
{
  private readonly Config _config;
  private readonly GitHubClient _gitClient;
  public List<Repository> Repositories { get; set; }

  public OctokitGithubClient(IOptions<Config> options)
  {
    _config = options.Value;

    var ghe = new Uri(_config.apiUrl);
    _gitClient= new GitHubClient(new ProductHeaderValue("web-app-v1"), ghe);

    var tokenAuth = new Credentials(_config.PAT.git);
    _gitClient.Credentials = tokenAuth;

  }

  public async Task<List<Repository>> getGithubRepository()
  { 
    var data = _gitClient.Repository.GetAllForCurrent();
    Repositories = new List<Repository>(data);   
    return Repositories;
  }
}

And I get this error message:

error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<Octokit.Repository>' to 'Octokit.Repository' [/root/projects/WebAppProject/src/Web.Git.Api/Web.Git.Api.csproj]

Can someone please give me a hint? I was looking through Octokit doc but I can't find API documentations. Ty!

1

There are 1 best solutions below

0
On

You can read more about asynchronous programming in C#. Here is a good place to start.

GetAllForCurrent() signature is Task<IReadOnlyList<Repository>> GetAllForCurrent(); If we want to use this asynchronously, we use await and then we convert IReadOnlyList<Repository> to List<Repository> using ToList()

public async Task<List<Repository>> GetGithubRepositoryAsync()
{
    var repos = await _gitClient.Repository.GetAllForCurrent();
    return repos.ToList();
}

If we want to use it synchronously, one way is to use Result of the Task<>

public List<Repository> GetGithubRepository()
{
    return _gitClient.Repository.GetAllForCurrent().Result.ToList();
}

As mentioned in this link using Result property is not recommended

The Result property is a blocking property. If you try to access it before its task is finished, the thread that's currently active is blocked until the task completes and the value is available. In most cases, you should access the value by using await instead of accessing the property directly.