1

I would like to control the way how OWIN creates registered middlewares. For example when using following code to register MyCustomMiddleware:

app.Use<MyCustomMiddleware>();

I want to be the one who calls MyCustomMiddleware constructor and pass all needed arguments. As a motivation please imagine for example following scenarios:

  • MyCustomMiddleware constructor requires some arguments that should be created based on current request,
  • Arguments should be resolved from from DI container,
  • I would like to control lifetime of MyCustomMiddleware.

I have found out some comments on how to use OWIN with SimpleInjector or Ninject. However I was not able to find anything independent on particular DI library.

Ondra Netočný
  • 410
  • 3
  • 16

1 Answers1

2
app.Use((c, next) =>
{
    IMiddleware middleware = new MyCustomMiddleware(...);
    return middleware.InvokeAsync(c, _ => next());
});
Steven
  • 166,672
  • 24
  • 332
  • 435
  • Thank you, however this will not work for cases when I want to use `app.Use()` or `app.Use(typeof(MyCustomMiddleware))`. – Ondra Netočný Oct 30 '20 at 16:19
  • Either you supply the type and the framework will create the type for you using reflection, or you use the approach I presented here, which allows you to call the constructor yourself. These are your options. – Steven Oct 30 '20 at 16:27