Skip to content

Instantly share code, notes, and snippets.

@loudej
Created October 3, 2013 18:13
Show Gist options
  • Save loudej/6814365 to your computer and use it in GitHub Desktop.
Save loudej/6814365 to your computer and use it in GitHub Desktop.

And for the highest degree of compatability consider sticking to the owin func<dict, task> signature as a middleware constructor, and add an extension method to IAppBuilder for discoverability.

In the following example, a Microsoft.Owin.dll reference is used only for the OwinContext/OwinRequest/OwinResponse helper classes. Those will work regardless of if the host is aware of the OwinMiddleware base class. That reference can be avoided altogether if your project has its own internal copy of an environment wrapper class it uses, instead of OwinContext.

Also in the example, an Owin.dll reference is used to add app.UseExample([options]) extension method to IAppBuilder. Without that extension method the site author could still call app.Use([options]) or app.Use(typeof(ExampleMiddleware)[, options]), but the discoverability is not good.

So, we’d suggest middleware authors take a dependency on Owin.dll to provide an IAppBuilder extension method at a minimum, and host authors to use IAppBuilder as the argument to Startup.Configuration code, as the min bar for interoperability and convenience. Small footnote – Owin.dll contains only the single interface IAppBuilder, and no implementation, so there should be virtually no reason to rev that assembly.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Owin;
using AnExample;
namespace AnExample
{
public class ExampleMiddlware
{
private readonly Func<IDictionary<string, object>, Task> _next;
private readonly string _options;
public ExampleMiddlware(Func<IDictionary<string, object>, Task> next)
{
_next = next;
}
public ExampleMiddlware(Func<IDictionary<string, object>, Task> next, string options)
{
_next = next;
_options = options;
}
public async Task Invoke(IDictionary<string, object> env)
{
var context = new OwinContext(env);
// todo: handle incoming request
await _next(env);
// todo: observe outgoing response
}
}
}
namespace Owin
{
public static class ExampleExtensions
{
public static IAppBuilder UseExample(this IAppBuilder app)
{
app.Use(typeof(ExampleMiddlware));
return app;
}
public static IAppBuilder UseExample(this IAppBuilder app, string options)
{
app.Use(typeof(ExampleMiddlware), options);
return app;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment