The Wayback Machine - https://web.archive.org/web/20230117162936/https://docs.github.com/fr/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/setting-up-your-dotnet-project-for-codespaces
Skip to main content

Setting up a C# (.NET) project for GitHub Codespaces

Get started with a C# (.NET) project in GitHub Codespaces by creating a custom dev container configuration.

Introduction

This tutorial guide shows you how to set up an example C# (.NET) project Dans Codespaces, utilisez l’application de bureau Visual Studio Code ou le client web VS Code. Il vous guidera dans un exemple pour ouvrir votre projet dans un codespace et ajouter et modifier une configuration de conteneur de développement prédéfinie.

Step 1: Open the project in a codespace

  1. Go to https://github.com/microsoft/vscode-remote-try-dotnet.

  2. Click Use this template, then click Open in a codespace.

    Screenshot of the 'Use this template' button and dropdown menu

When you create a codespace, your project is created on a remote virtual machine that is dedicated to you. By default, the container for your codespace has many languages and runtimes, including .NET. It also includes a common set of tools like git, wget, rsync, openssh, and nano.

Vous pouvez personnaliser votre codespace en ajustant le nombre de processeurs virtuels et la RAM, en ajoutant des dotfiles pour personnaliser votre environnement, ou en modifiant les outils et les scripts installés.

Codespaces utilise un fichier appelé devcontainer.json pour configurer le conteneur de développement que vous utilisez lorsque vous travaillez dans un codespace. Chaque référentiel peut contenir un ou plusieurs fichiers devcontainer.json pour vous fournir l’environnement de développement dont vous avez précisément besoin pour travailler sur votre code dans un codespace.

Lors du lancement, Codespaces utilise un fichier devcontainer.json, ainsi que tous les fichiers dépendants qui composent la configuration du conteneur de développement, pour installer des outils et des runtimes, et effectuer d’autres tâches de configuration nécessaires au projet. Pour plus d’informations, consultez « Présentation des conteneurs de développement ».

Step 2: Add a dev container configuration

The default development container, or "dev container," for GitHub Codespaces comes with the latest .NET version and common tools preinstalled. However, we recommend that you configure your own dev container to include all of the tools and scripts your project needs. This will ensure a fully reproducible environment for all GitHub Codespaces users in your repository.

Pour configurer votre dépôt afin d’utiliser un conteneur de développement personnalisé, vous devez créer un ou plusieurs fichiers devcontainer.json. Vous pouvez les ajouter à partir d’un modèle de configuration prédéfini, dans Visual Studio Code, où écrire les vôtres. Pour plus d’informations sur les configurations de conteneurs de développement, consultez « Présentation des conteneurs de développement ».

  1. Accédez à la Visual Studio Code Command Palette (Maj+Commande+P (Mac) / Ctrl+Maj+P (Windows/Linux)), puis commencez à taper « dev container ». Sélectionnez Codespaces : Ajouter des fichiers config de conteneur de développement.

    « Codespaces : Ajouter des fichiers config de conteneur de développement » dans la Visual Studio Code Command Palette

  2. Type c# and click C# (.NET). Other options are available if your project uses particular tools. For example, C# and MS SQL.

    Screenshot of the 'C# (.NET)' option

  3. Click the latest version of .NET.

    Screenshot of the Node.js version selection

  4. A list of additional features is displayed. We'll install the .NET CLI, a command-line interface for developing, building, running, and publishing .NET applications. To install this tool, type dotnet, select Dotnet CLI, then click OK.

    Screenshot of additional features for 'dotnet'

  5. A message is displayed telling you that the dev container configuration file already exists. Click Overwrite.

    A devcontainer.json file is created and is opened in the editor.

Details of your custom dev container configuration

If you look in the Visual Studio Code Explorer you'll see that a .devcontainer directory has been added to the root of your project's repository containing the devcontainer.json file. This is the main configuration file for codespaces created from this repository.

devcontainer.json

The devcontainer.json file that you have added will contain values for the name, image, and features properties. Some additional properties that you may find useful are included but are commented out.

The file will look similar to this, depending on which image you chose:

// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
{
  "name": "C# (.NET)",
  // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
  "image": "mcr.microsoft.com/devcontainers/dotnet:0-7.0",
  "features": {
    "ghcr.io/devcontainers/features/dotnet:1": {}
  }

  // Features to add to the dev container. More info: https://containers.dev/features.
  // "features": {},

  // Use 'forwardPorts' to make a list of ports inside the container available locally.
  // "forwardPorts": [5000, 5001],
  // "portsAttributes": {
  //   "5001": {
  //     "protocol": "https"
  //   }
  // }

  // Use 'postCreateCommand' to run commands after the container is created.
  // "postCreateCommand": "dotnet restore",

  // Configure tool-specific properties.
  // "customizations": {},

  // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
  // "remoteUser": "root"
}
  • name: You can name your dev container anything you want. A default value is supplied.
  • image: The name of an image in a container registry (DockerHub, GitHub Container registry, or Azure Container Registry) that will be used to create the dev container for the codespace.
  • features: A list of one or more objects, each of which references one of the available dev container features. Features are self-contained, shareable units of installation code and development container configuration. They provide an easy way to add more tooling, runtime, or library features to your development container. For more information, see "Available Dev Container Features" on the Development Containers website. You can add features by going to the VS Code Command Palette and typing features.
  • forwardPorts: Any ports listed here will be forwarded automatically. For more information, see "Forwarding ports in your codespace."
  • portsAttributes - This property maps a specified port to one or more default options. For more information, see the dev containers specification on the Development Containers website.
  • postCreateCommand: Use this property to run commands after your codespace is created.
  • customizations: This property allows you to customize a specific tool or service when it is used for working in a codespace. For example, you can configure specific settings and extensions for VS Code. For more information, see "Supporting tools and services" on the Development Containers website.
  • remoteUser: By default, you’re running as the vscode user, but you can optionally set this to root.

For a complete list of available properties, see the dev containers specification on the Development Containers website.

Additional dev container configuration files

If you are familiar with Docker, you may want to use a Dockerfile, or Docker Compose, to configure your codespace environment, in addition to the devcontainer.json file. You can do this by adding your Dockerfile or docker-compose.yml files alongside the devcontainer.json file. For more information, see "Using Images, Dockerfiles, and Docker Compose" on the Development Containers website.

Step 3: Modify your devcontainer.json file

With your dev container configuration added and a basic understanding of what everything does, you can now make changes to customize your environment further. In this example, you'll add properties that will:

  • Forward the port on which the application runs on the remote machine to your local machine.
  • Run dotnet restore, after the dev container is created, to restore the dependencies required by the application.
  • Automatically install a VS Code extension in this codespace.
  1. In the devcontainer.json file, add a comma after the features property, and delete the two commented out lines about features.

    JSON
      "features": {
        "ghcr.io/devcontainers/features/dotnet:1": {}
      },
    
      // Features to add to the dev container. More info: https://containers.dev/features.
      // "features": {},
  2. Uncomment the forwardPorts property and change its value to port 5000 only.

    JSON
    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    "forwardPorts": [5000],
  3. Uncomment the postCreateCommand property.

    JSON
    // Use 'postCreateCommand' to run commands after the container is created.
    "postCreateCommand": "dotnet restore",
  4. Uncomment the customizations property and edit it as follows to install the "Code Spell Checker" VS Code extension.

    JSON
    // Configure tool-specific properties.
    "customizations": {
      // Configure properties specific to VS Code.
      "vscode": {
        // Add the IDs of extensions you want installed when the container is created.
        "extensions": [
          "streetsidesoftware.code-spell-checker"
        ]
      }
    }

    The devcontainer.json file should now look similar to this, depending on which image you chose:

    // For format details, see https://aka.ms/devcontainer.json. For config options, see the
    // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
    {
      "name": "C# (.NET)",
      // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
      "image": "mcr.microsoft.com/devcontainers/dotnet:0-7.0",
      "features": {
        "ghcr.io/devcontainers/features/dotnet:1": {}
      },
    
      // Use 'forwardPorts' to make a list of ports inside the container available locally.
      "forwardPorts": [5000],
      // "portsAttributes": {
      //   "5001": {
      //     "protocol": "https"
      //   }
      // }
    
      // Use 'postCreateCommand' to run commands after the container is created.
      "postCreateCommand": "dotnet restore",
    
      // Configure tool-specific properties.
      "customizations": {
        // Configure properties specific to VS Code.
        "vscode": {
          // Add the IDs of extensions you want installed when the container is created.
          "extensions": [
            "streetsidesoftware.code-spell-checker"
          ]
        }
      }
    
      // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
      // "remoteUser": "root"
    }
    
  5. Save your changes.

  6. Accédez à la VS Code Command Palette (Maj+Commande+P (Mac)/Ctrl+Maj+P (Windows/Linux)), puis commencez à taper « regénérer ». Sélectionnez Codespaces : Regénérer le conteneur.

    Capture d'écran de la commande Rebuild Container dans la palette de commandes

    Conseil : vous souhaiterez parfois effectuer une régénération complète pour vider votre cache et régénérer votre conteneur avec de nouvelles images. Pour plus d'informations, consultez la section « Effectuer une régénération complète d'un conteneur ».

    La reconstruction à l’intérieur de votre espace de code garantit que vos modifications fonctionnent comme prévu avant de valider les modifications dans le référentiel. Si quelque chose entraîne un échec, vous serez placé dans un espace de code avec un conteneur de récupération à partir duquel vous pouvez reconstruire pour ajuster votre conteneur.

    After the dev container is rebuilt, and your codespace becomes available again, the postCreateCommand will have been run, restoring the required dependencies, and the "Code Spell Checker" extension will be available for use.

Step 4: Run your application

In the previous section, you used the postCreateCommand to install a set of packages via the dotnet restore command. With the dependencies now installed, you can run the application.

  1. Run the application by pressing F5 or entering dotnet watch run in the Terminal.

  2. When the application starts, click the Ports tab, right-click port 5000 and click Open in Browser.

    Screenshot of the 'Open in Browser' option

Step 5: Commit your changes

Après avoir apporté des modifications à votre codespace (nouveau code ou modifications de configuration), vous souhaiterez valider vos modifications. La validation des modifications apportées à votre référentiel permet de veiller à ce que toute autre personne qui crée un codespace à partir de ce référentiel dispose de la même configuration. De plus, toute personnalisation que vous effectuez, ajout d’extensions VS Code par exemple, s’affiche pour tous les utilisateurs.

Pour plus d’informations, consultez « Utilisation d’un contrôle de code source dans votre codespace ».

Next steps

You should now be able to add a custom dev container configuration to your own C# (.NET) project.