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

Add UseMiddleware(Container) extension method to ASP.NET Core integration package #513

Closed
dotnetjunkie opened this Issue Feb 7, 2018 · 0 comments

Comments

1 participant
@dotnetjunkie
Collaborator

dotnetjunkie commented Feb 7, 2018

To simplify working with middleware, the ASP.NET Core integration package should contain an extension method that:

  • Registers the middleware component as root type in the Simple Injector container.
  • Adds the middleware component to the ASP.NET Core pipeline, just like app.Use would do.

The implementation should look something similar to the following:

public static void UseMiddleware<TMiddleware>(this IApplicationBuilder app, Container container)
    where TMiddleware : class, IMiddleware
{
    var lifestyle =
        container.Options.LifestyleSelectionBehavior.SelectLifestyle(typeof(TMiddleware));
    var producer = lifestyle.CreateProducer<IMiddleware, TMiddleware>(container);

    app.Use((c, next) => producer.GetInstance().InvokeAsync(c, _ => next()));
}

Or the simplified, but slightly slower:

public static void UseMiddleware<TMiddleware>(this IApplicationBuilder app, Container container)
    where TMiddleware : class, IMiddleware
{
    container.Register<TMiddleware>();

    app.Use((c, next) => container.GetInstance<TMiddleware>().InvokeAsync(c, _ => next()));
}

The latter example doesn't allow applying IMiddleware decorators to a middleware component, but I'm unsure whether that would actually be a problem, since the middleware is in fact very similar to a decorator, and it would be unlikely to want to wrap middleware components in decorators.

Do note that IMiddleware is a framework provided interface that has been made available with the introduction of ASP.NET Core 2.0. This means that the introduction of this extension method does mean the package (and all its dependencies) will only be compatible with .NET Core 2.0 and up.

@dotnetjunkie dotnetjunkie added this to the v4.1 milestone Feb 7, 2018

dotnetjunkie added a commit that referenced this issue Feb 25, 2018

dotnetjunkie added a commit that referenced this issue Feb 25, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment