Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GitAuto: [FEATURE] Add custom IoC Container support with HostBuilder.UseServiceProviderFactory method #577

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

gitauto-ai[bot]
Copy link
Contributor

@gitauto-ai gitauto-ai bot commented Oct 22, 2024

Resolves #170

What is the feature

Implement support for a custom Inversion of Control (IoC) container by integrating the .NET method HostBuilder.UseServiceProviderFactory. This feature introduces a custom service provider factory that allows the application to use a tailor-made IoC container, aligning with standards from established IoC libraries without relying on external dependencies.

Why we need the feature

Our current service registry lacks support for UseServiceProviderFactory, limiting our flexibility in dependency management and service configuration. By implementing a custom IoC container, we can:

  • Enhance Dependency Management: Provide advanced techniques for managing dependencies, including modular registrations and custom lifecycles.
  • Increase Flexibility: Allow developers to customize how services are registered and resolved, accommodating complex scenarios.
  • Align with Best Practices: Follow established patterns from well-known IoC containers, improving code maintainability and scalability.
  • Avoid External Dependencies: Achieve the benefits of popular IoC libraries without adding external library dependencies to the project.

How to implement and why

Step 1: Design a Custom IoC Container

  • Create Core Functionality:

    • Implement classes for dependency registration, resolution, and lifecycle management (singleton, scoped, transient).
    • Ensure the container supports generic type registration and open generic types.
  • Adhere to Standards:

    • Follow design patterns from libraries like Autofac and Castle Windsor, such as fluent interfaces for registration and support for advanced scenarios.
    • Implement service interception and decorators if necessary.

Step 2: Implement the UseServiceProviderFactory Method

  • Create the Service Provider Factory:

    • Implement the IServiceProviderFactory<TContainerBuilder> interface with our custom container builder.
    • Example:
      public class CustomServiceProviderFactory : IServiceProviderFactory<CustomContainerBuilder>
      {
          public CustomContainerBuilder CreateBuilder(IServiceCollection services)
          {
              var builder = new CustomContainerBuilder();
              builder.Populate(services);
              return builder;
          }
      
          public IServiceProvider CreateServiceProvider(CustomContainerBuilder containerBuilder)
          {
              return containerBuilder.BuildServiceProvider();
          }
      }
  • Integrate with HostBuilder:

    • Modify the application's entry point to use the custom service provider factory.
      public static IHostBuilder CreateHostBuilder(string[] args) =>
          Host.CreateDefaultBuilder(args)
              .UseServiceProviderFactory(new CustomServiceProviderFactory())
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  webBuilder.UseStartup<Startup>();
              });

Step 3: Extend Service Registration Capabilities

  • Implement Registration Methods:

    • Provide methods for registering services with different lifetimes and options.
      public class CustomContainerBuilder
      {
          public void RegisterTransient<TService, TImplementation>() where TImplementation : TService
          {
              // Implementation
          }
      
          public void RegisterScoped<TService, TImplementation>() where TImplementation : TService
          {
              // Implementation
          }
      
          public void RegisterSingleton<TService, TImplementation>() where TImplementation : TService
          {
              // Implementation
          }
      
          public void Populate(IServiceCollection services)
          {
              // Transfer registrations from IServiceCollection to the custom container
          }
      
          public IServiceProvider BuildServiceProvider()
          {
              // Build and return the IServiceProvider
          }
      }
  • Support Advanced Features:

    • Enable open generic registrations, conditional registrations, and constructor injection.

Step 4: Test the Integration Thoroughly

  • Unit Testing:

    • Write unit tests to verify that services are registered and resolved correctly.
    • Test different lifecycles and ensure that scoped services behave as expected.
  • Integration Testing:

    • Validate that the application starts up correctly using the custom IoC container.
    • Ensure that middleware and other framework integrations work without issues.

Step 5: Documentation and Examples

  • Provide Clear Documentation:

    • Explain how to register and resolve services using the new IoC container.
    • Include examples of common scenarios and best practices.
  • Update Existing Documentation:

    • Modify any existing documentation to reflect the new options available for dependency injection.

About backward compatibility

The introduction of the custom IoC container is designed to be fully backward compatible:

  • Optional Adoption: Existing applications can continue using the default service provider without any changes. The custom IoC container is an opt-in feature.
  • Non-Intrusive Changes: The implementation does not alter existing service registrations or resolutions unless the custom service provider factory is explicitly used.
  • Compatibility Layer: The custom container will respect the registrations made in IServiceCollection, ensuring that services behave as before unless overridden.
  • Gradual Migration: Developers can migrate to the custom IoC container at their own pace, testing and verifying functionality in stages.

By ensuring backward compatibility, we allow current users to benefit from the new feature without disrupting existing functionality.

Test these changes locally

git checkout -b gitauto/issue-#170-eb0577d7-c1a9-4900-b082-96a8cc77ee04
git pull origin gitauto/issue-#170-eb0577d7-c1a9-4900-b082-96a8cc77ee04

@github-actions github-actions bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Oct 22, 2024
Copy link
Contributor

Infisical secrets check: ✅ No secrets leaked!

💻 Scan logs
12:10AM INF scanning for exposed secrets...
12:10AM INF 564 commits scanned.
12:10AM INF scan completed in 688ms
12:10AM INF no leaks found

Copy link

sonarcloud bot commented Oct 22, 2024

Copy link

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
-0.10% (target: -1.00%)
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (403901b) 3874 1642 42.39%
Head commit (0e59903) 3874 (+0) 1638 (-4) 42.28% (-0.10%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#577) 0 0 ∅ (not applicable)

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

Codacy stopped sending the deprecated coverage status on June 5th, 2024. Learn more

@AppVeyorBot
Copy link

Build CrispyWaffle 8.2.198 failed (commit 4c492e73b5 by @gitauto-ai[bot])

@gstraccini gstraccini bot added .NET Pull requests that update .net code DI gitauto GitAuto label to trigger the app in a issue. good first issue Good for newcomers hacktoberfest Participation in the Hacktoberfest event help wanted Extra attention is needed IoC question Further information is requested labels Oct 22, 2024
@gstraccini gstraccini bot requested a review from guibranco October 22, 2024 02:12
@gstraccini gstraccini bot added 🚦 awaiting triage Items that are awaiting triage or categorization 🤖 bot Automated processes or integrations labels Oct 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🚦 awaiting triage Items that are awaiting triage or categorization 🤖 bot Automated processes or integrations DI gitauto GitAuto label to trigger the app in a issue. good first issue Good for newcomers hacktoberfest Participation in the Hacktoberfest event help wanted Extra attention is needed IoC .NET Pull requests that update .net code question Further information is requested size/L Denotes a PR that changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[FEATURE] Add custom IoC Container support with HostBuilder.UseServiceProviderFactory method
2 participants