dotnet-best-practices — скилл для GitHub Copilot
Проверяет выделенный .NET/C# код по правилам проекта: от структуры и DI до тестов, логирования и безопасности. Нужен при ревью или доработке решения.
npx skills add github/awesome-copilot --skill dotnet-best-practicesЧто делает dotnet-best-practices
Скилл направляет GitHub Copilot при работе с выделенным C# кодом. Он требует XML-документацию для публичных API, структуру пространств имён {Core|Console|App|Service}.{Feature}, осмысленные имена и небольшие связные методы. Для сложного создания объектов предлагает Factory, а для команд — Command Handler с обобщённым базовым классом.
В правилах есть DI через конструктор с ArgumentNullException, времена жизни сервисов Microsoft.Extensions.DependencyInjection и интерфейсы для тестирования. Скилл охватывает async/await, Task, ConfigureAwait(false), локализацию через ResourceManager, типизированную конфигурацию и appsettings.json. Также он задаёт MSTest, FluentAssertions, Moq и AAA-подход для тестов.
Отдельно проверяются структурированное логирование, конкретные исключения, валидация и параметризованные запросы. Есть рекомендации для Microsoft.SemanticKernel, включая настройки ChatCompletion и Embedding. Ставить стоит командам, которые уже придерживаются этих библиотек и паттернов; для проекта с другими тестовыми или DI-правилами скилл будет навязывать неподходящий стиль.
Какие задачи решает
- добавить XML-комментарии к публичному API
- оформить внедрение зависимостей через конструктор
- покрыть сценарии успеха и ошибки тестами MSTest
- перевести I/O-код на async/await
- настроить структурированное логирование и конкретные исключения
Примеры запросов агенту
- Проверь выделенный C# код по правилам dotnet-best-practices.
- Добавь XML-документацию и исправь DI в этом классе.
- Напиши MSTest-тесты с FluentAssertions и Moq для обработчика команды.
Как установить dotnet-best-practices
1Через Skills CLI (Vercel)
npx skills add github/awesome-copilot --skill dotnet-best-practices2GitHub CLI
gh skill install github/awesome-copilot dotnet-best-practices3Вручную: положить файлы
.github/skills/dotnet-best-practices/SKILL.md1Через Skills CLI (Vercel)
npx skills add github/awesome-copilot --skill dotnet-best-practices -a claude-code2Вручную: положить файлы
~/.claude/skills/dotnet-best-practices/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/dotnet-best-practices/
Вручную: положить файлы
.agents/skills/dotnet-best-practices/SKILL.mdДля всех проектов — ~/.agents/skills/
Вручную: положить файлы
.cursor/skills/dotnet-best-practices/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
Командой платформы
gemini skills install https://github.com/github/awesome-copilot --path skills/dotnet-best-practicesВручную: положить файлы
.devin/skills/dotnet-best-practices/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
Из того же набора554
Весь набор →Похожие
Вопросы о dotnet-best-practices
Как установить dotnet-best-practices в GitHub Copilot?
Выполните npx skills add github/awesome-copilot --skill dotnet-best-practices. Также доступна команда gh skill install github/awesome-copilot dotnet-best-practices.
Что делает dotnet-best-practices?
Скилл задаёт правила для .NET/C# кода в выделенном фрагменте: документация, архитектура, DI, асинхронность, тестирование, конфигурация и обработка ошибок.
Какие тестовые инструменты предлагает dotnet-best-practices?
Правила используют MSTest и FluentAssertions, а зависимости предлагают подменять через Moq. Тесты строятся по схеме Arrange, Act, Assert и должны включать успешные и ошибочные сценарии.
Исходный текст
SKILL.md · MIT
---
name: dotnet-best-practices
description: 'Ensure .NET/C# code meets best practices for the solution/project.'
---
# .NET/C# Best Practices
Your task is to ensure .NET/C# code in ${selection} meets the best practices specific to this solution/project. This includes:
## Documentation & Structure
- Create comprehensive XML documentation comments for all public classes, interfaces, methods, and properties
- Include parameter descriptions and return value descriptions in XML comments
- Follow the established namespace structure: {Core|Console|App|Service}.{Feature}
## Design Patterns & Architecture
- Use primary constructor syntax for dependency injection (e.g., `public class MyClass(IDependency dependency)`)
- Implement the Command Handler pattern with generic base classes (e.g., `CommandHandler<TOptions>`)
- Use interface segregation with clear naming conventions (prefix interfaces with 'I')
- Follow the Factory pattern for complex object creation.
## Dependency Injection & Services
- Use constructor dependency injection with null checks via ArgumentNullException
- Register services with appropriate lifetimes (Singleton, Scoped, Transient)
- Use Microsoft.Extensions.DependencyInjection patterns
- Implement service interfaces for testability
## Resource Management & Localization
- Use ResourceManager for localized messages and error strings
- Separate LogMessages and ErrorMessages resource files
- Access resources via `_resourceManager.GetString("MessageKey")`
## Async/Await Patterns
- Use async/await for all I/O operations and long-running tasks
- Return Task or Task<T> from async methods
- Use ConfigureAwait(false) where appropriate
- Handle async exceptions properly
## Testing Standards
- Use MSTest framework with FluentAssertions for assertions
- Follow AAA pattern (Arrange, Act, Assert)
- Use Moq for mocking dependencies
- Test both success and failure scenarios
- Include null parameter validation tests
## Configuration & Settings
- Use strongly-typed configuration classes with data annotations
- Implement validation attributes (Required, NotEmptyOrWhitespace)
- Use IConfiguration binding for settings
- Support appsettings.json configuration files
## Semantic Kernel & AI Integration
- Use Microsoft.SemanticKernel for AI operations
- Implement proper kernel configuration and service registration
- Handle AI model settings (ChatCompletion, Embedding, etc.)
- Use structured output patterns for reliable AI responses
## Error Handling & Logging
- Use structured logging with Microsoft.Extensions.Logging
- Include scoped logging with meaningful context
- Throw specific exceptions with descriptive messages
- Use try-catch blocks for expected failure scenarios
## Performance & Security
- Use C# 12+ features and .NET 8 optimizations where applicable
- Implement proper input validation and sanitization
- Use parameterized queries for database operations
- Follow secure coding practices for AI/ML operations
## Code Quality
- Ensure SOLID principles compliance
- Avoid code duplication through base classes and utilities
- Use meaningful names that reflect domain concepts
- Keep methods focused and cohesive
- Implement proper disposal patterns for resources
© github · MIT · github/awesome-copilot