Code Standards
.NET Blazor Coding Standards
1. Project Structure
Organize by Feature: Group related components, services, and models into feature folders.
Naming Conventions: Use PascalCase for namespaces, classes, and methods. Use camelCase for private fields and variables.
2. Components
Naming: Use descriptive names ending with “Component” (e.g.,
UserProfileComponent
).File Structure: Each component should have its own
.razor
file and an optional.razor.cs
file for code-behind.Lifecycle Methods: Override lifecycle methods like
OnInitializedAsync
andOnParametersSetAsync
for initialization and parameter updates.
3. Services
Dependency Injection: Use dependency injection for services. Register services in
Startup.cs
orProgram.cs
.Singleton vs Scoped: Use singleton services for state management and scoped services for per-request operations.
4. Data Binding
One-Way Binding: Use one-way binding (
@bind-Value
) for read-only data.Two-Way Binding: Use two-way binding (
@bind-Value
) for editable data.
5. Event Handling
Event Callbacks: Use
EventCallback
for parent-child communication.Async Methods: Use
async
methods for event handlers and avoid blocking calls.
6. Styling
CSS Isolation: Use CSS isolation (
.razor.css
) for component-specific styles.Class Naming: Follow BEM (Block, Element, Modifier) methodology for class names.
7. Error Handling
Try-Catch: Use try-catch blocks for error-prone code.
Logging: Use built-in logging services to log errors and important events.
8. Testing
Unit Tests: Write unit tests for services and business logic.
Component Tests: Use bUnit for Blazor component testing.
9. Code Quality
Code Reviews: Conduct regular code reviews to ensure code quality and adherence to standards.
Static Analysis: Use tools like SonarQube or Resharper for static code analysis.
10. Documentation
XML Comments: Use XML comments for public methods and classes.
README: Maintain a README file with project setup and usage instructions.