An open API service indexing awesome lists of open source software.

https://github.com/mreshboboyev/factory-pattern

A .NET application implementing the Factory Pattern to generate invoices in various formats (PDF, TXT, CSV). Utilizes QuestPDF for creating professional PDF documents and the Repository Pattern for organized and maintainable data access.
https://github.com/mreshboboyev/factory-pattern

aspnet-core csv design-patterns dotnet-core factory-pattern file-generation invoice-generation pdf-generation questpdf repository-pattern text

Last synced: 27 days ago
JSON representation

A .NET application implementing the Factory Pattern to generate invoices in various formats (PDF, TXT, CSV). Utilizes QuestPDF for creating professional PDF documents and the Repository Pattern for organized and maintainable data access.

Awesome Lists containing this project

README

          

# Factory Pattern Showcase: Advanced Implementation

This project demonstrates a sophisticated .NET implementation of the Factory Pattern to generate invoices in multiple file formats (PDF, TXT, and CSV). It showcases the true power and flexibility of the Factory Pattern in enterprise-level applications.

## 🚀 Key Features

### Factory Pattern Excellence
- **Advanced Factory Implementation**: Fully-featured factory with logging, validation, and extensibility
- **Decoupled Architecture**: Client code is completely decoupled from concrete implementations
- **Centralized Object Creation**: All object instantiation logic is centralized in the factory
- **Easy Extensibility**: Adding new formats requires minimal code changes
- **Dependency Injection Integration**: Seamless integration with .NET DI container

### API Documentation
- **NSwag Integration**: Comprehensive API documentation with Swagger UI
- **Interactive API Testing**: Built-in Swagger UI for testing endpoints
- **Detailed Endpoint Documentation**: Rich documentation for all API endpoints

### Format Generation
- **PDF Generation**: Professional-grade PDF documents using QuestPDF
- **CSV Generation**: Structured comma-separated data format
- **TXT Generation**: Simple text-based invoice output

## 🏗️ Architecture Overview

The Factory Pattern implementation in this project demonstrates several advanced concepts:

1. **Interface-Based Design**: All generators implement the [IInvoiceGenerator](FactoryPattern.API/Abstracts/IInvoiceGenerator.cs) interface
2. **Factory Interface**: The [IInvoiceGeneratorFactory](FactoryPattern.API/Abstracts/IInvoiceGeneratorFactory.cs) defines the contract for creating generators
3. **Concrete Factory**: The [InvoiceGeneratorFactory](FactoryPattern.API/Factories/InvoiceGeneratorFactory.cs) implements the factory logic with additional utility methods
4. **Dependency Injection**: All components are registered with the .NET DI container for proper lifecycle management

## 📦 Prerequisites

- [.NET 9.0 or higher](https://dotnet.microsoft.com/download)

## 🛠️ Installation

1. Clone the repository:
```bash
git clone https://github.com/MrEshboboyev/FactoryPattern.git
```
2. Navigate to the project directory:
```bash
cd FactoryPattern
```
3. Restore dependencies:
```bash
dotnet restore
```

## 🚀 Usage

### Running the Application

Start the application:
```bash
cd FactoryPattern.API
dotnet run
```

The application will start on `http://localhost:5143` by default.

### API Endpoints

#### Generate Invoice
```
GET /api/invoice/{id:guid}/{format}
```
Generates an invoice in the specified format using the Factory Pattern.

Parameters:
- `id`: The unique identifier for the invoice (GUID)
- `format`: The format in which to generate the invoice (Pdf, Txt, Csv)

Example:
```
GET /api/invoice/123e4567-e89b-12d3-a456-426614174000/Pdf
```

#### Get Supported Formats
```
GET /api/invoice/formats
```
Returns a list of all invoice formats supported by the Factory Pattern implementation.

### Factory Pattern in Action

The application uses the Factory Pattern to create appropriate invoice generators based on the requested format:

```csharp
// Client code is completely decoupled from concrete implementations
var generator = invoiceGeneratorFactory.CreateInvoiceGenerator(format);
var invoiceData = generator.GenerateInvoice(id);
var contentType = generator.GetContentType();

var fileName = $"Invoice_{id}.{format.ToString().ToLower()}";
return Results.File(invoiceData, contentType, fileName);
```

## 🔧 Extending the Factory Pattern

To add support for a new file format:

1. Create a new class implementing the [IInvoiceGenerator](FactoryPattern.API/Abstracts/IInvoiceGenerator.cs) interface:
```csharp
public class ExcelInvoiceGenerator : IInvoiceGenerator
{
public byte[] GenerateInvoice(Guid invoiceId)
{
// Implementation for generating Excel invoice
}

public string GetContentType() => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
```

2. Add the new file type to the [InvoiceFormat](FactoryPattern.API/Enums/InvoiceFormat.cs) enum:
```csharp
public enum InvoiceFormat
{
Pdf,
Txt,
Csv,
Excel // New format
}
```

3. Update the [InvoiceGeneratorFactory](FactoryPattern.API/Factories/InvoiceGeneratorFactory.cs) to include the new type:
```csharp
public IInvoiceGenerator CreateInvoiceGenerator(InvoiceFormat invoiceFormat)
{
return invoiceFormat switch
{
InvoiceFormat.Pdf => _serviceProvider.GetRequiredService(),
InvoiceFormat.Txt => _serviceProvider.GetRequiredService(),
InvoiceFormat.Csv => _serviceProvider.GetRequiredService(),
InvoiceFormat.Excel => _serviceProvider.GetRequiredService(), // New format
_ => throw new ArgumentException("Invalid/Unsupported invoice format", nameof(invoiceFormat))
};
}
```

4. Register the new generator in [Program.cs](FactoryPattern.API/Program.cs):
```csharp
builder.Services.AddTransient();
```

## 📚 Benefits of This Factory Pattern Implementation

1. **Single Responsibility Principle**: Each generator focuses solely on its specific format
2. **Open/Closed Principle**: Easy to extend without modifying existing code
3. **Loose Coupling**: Client code depends on abstractions, not concrete implementations
4. **Testability**: Each component can be easily unit tested
5. **Maintainability**: Changes to generation logic are isolated to specific classes
6. **Scalability**: New formats can be added without affecting existing functionality

## 📖 API Documentation

The project includes comprehensive API documentation powered by NSwag:

1. Start the application
2. Navigate to `http://localhost:5143/swagger` to access the Swagger UI
3. Explore and test all available endpoints

## 🤝 Contributing

Contributions are welcome! Follow these steps:
1. Fork the repository.
2. Create a feature branch: `git checkout -b feature-name`.
3. Commit your changes: `git commit -m "Add feature"`.
4. Push to the branch: `git push origin feature-name`.
5. Open a pull request.

## 📄 License

This project is licensed under the MIT License. See the `LICENSE` file for more details.

## 🙏 Acknowledgements

- [QuestPDF](https://www.questpdf.com/) - For excellent PDF generation capabilities
- [NSwag](https://github.com/RicoSuter/NSwag) - For API documentation generation
- [Factory Design Pattern](https://refactoring.guru/design-patterns/factory-method) - For the pattern inspiration

---

Happy coding! 🚀