Skip to content

Feature Request: Allow injection of existing IServiceCollection for dependency injection #4

@Cadtastic

Description

@Cadtastic

Description

Current Behavior

Currently, Console.Routing provides its own dependency injection mechanism through the RouterBuilder class with methods like .AddService<TService>(). This works well for basic scenarios but doesn't integrate with existing dependency injection containers that may already be configured elsewhere in the application.

Proposed Solution

Enhance Console.Routing to accept an already configured IServiceCollection (from Microsoft.Extensions.DependencyInjection) that would be used to resolve dependencies. This would allow Console.Routing to better integrate with applications that are already using the standard .NET dependency injection container.

Use Case

In larger applications where Console.Routing is just one component, we often have a central dependency injection container configured with all services. Having to register services again specifically for Console.Routing leads to:

  1. Duplicate service registration
  2. Potential inconsistencies between services
  3. Inability to leverage scoped services properly
  4. Additional maintenance burden when services change

Implementation Suggestion

Add a new method to the RouterBuilder class:

public RouterBuilder UseServiceCollection(IServiceCollection services)
{
    // Implementation that would use the provided service collection
    // instead of the internal service registry
    return this;
}

Or alternatively:

public RouterBuilder UseServiceProvider(IServiceProvider serviceProvider)
{
    // Implementation that would use the provided service provider
    // for resolving dependencies
    return this;
}

This would allow code like:

// Existing DI setup
var services = new ServiceCollection();
services.AddSingleton<IMyService, MyService>();
services.AddScoped<IUserService, UserService>();
var serviceProvider = services.BuildServiceProvider();

// Console.Routing setup using existing services
var router = new RouterBuilder()
    .AddAssemblyOf<Program>()
    .UseServiceProvider(serviceProvider)
    .Build();

Routing.Handle(args, router);

Additional Benefits

  1. Access to the full Microsoft.Extensions.DependencyInjection feature set
  2. Better integration with ASP.NET Core and other .NET applications
  3. Support for scoped lifetime services
  4. Consistency with modern .NET dependency injection practices

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions