Skip to content

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.

Notifications You must be signed in to change notification settings

MrEshboboyev/factory-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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 interface
  2. Factory Interface: The IInvoiceGeneratorFactory defines the contract for creating generators
  3. Concrete Factory: The InvoiceGeneratorFactory 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

🛠️ Installation

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

🚀 Usage

Running the Application

Start the application:

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:

// 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 interface:

    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 enum:

    public enum InvoiceFormat
    {
        Pdf, 
        Txt,
        Csv,
        Excel  // New format
    }
  3. Update the InvoiceGeneratorFactory to include the new type:

    public IInvoiceGenerator CreateInvoiceGenerator(InvoiceFormat invoiceFormat)
    {
        return invoiceFormat switch
        {
            InvoiceFormat.Pdf => _serviceProvider.GetRequiredService<PdfInvoiceGenerator>(),
            InvoiceFormat.Txt => _serviceProvider.GetRequiredService<TxtInvoiceGenerator>(),
            InvoiceFormat.Csv => _serviceProvider.GetRequiredService<CsvInvoiceGenerator>(),
            InvoiceFormat.Excel => _serviceProvider.GetRequiredService<ExcelInvoiceGenerator>(), // New format
            _ => throw new ArgumentException("Invalid/Unsupported invoice format", nameof(invoiceFormat))
        };
    }
  4. Register the new generator in Program.cs:

    builder.Services.AddTransient<ExcelInvoiceGenerator>();

📚 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


Happy coding! 🚀

About

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.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages