Skip to content

Provide access to IHost.Services inside 'UseMiddleware' method. #974

Description

@StevenRasmussen

Perhaps there's already a way to accomplish this but I was unable to figure it out. What I would like is:

commandLineBuilder.UseMiddleware(context =>
{
    //  'services' here would be the 'IHost.Services'
    var someService = services.GetService<ISomeService>();
}

I see that in the UseHost extension method, the IHost is placed in the BindingContext.ServiceProvider here:

invocation.BindingContext.AddService(typeof(IHost), _ => host);

However, the BindingContext.ServiceProvider is "internal" and so there's no way to get the IHost. Otherwise something like this would be possible:

commandLineBuilder.UseMiddleware(context =>
{
    var host = context.BindingContext.ServiceProvider.GetService<IHost>();
    var someService = host.Services.GetService<ISomeService>();
}

Directly exposing the BindingContext.ServiceProvider is probably not the answer... perhaps providing another extension method including the IHost.Services would be best (if it's possible):

public static CommandLineBuilder UseMiddleware(
    this CommandLineBuilder builder, 
    Action<InvocationContext> onInvoke, 
    IServiceProvider services, // IHost.Services
    MiddlewareOrder order = MiddlewareOrder.Default);

Or perhaps just the IHost itself:

public static CommandLineBuilder UseMiddleware(
    this CommandLineBuilder builder, 
    Action<InvocationContext> onInvoke, 
    IHost host,
    MiddlewareOrder order = MiddlewareOrder.Default);

I'd be happy to try and contribute a PR if some guidance is provided on direction here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions