Skip to content

IBuilder

Martin Halliday edited this page Aug 12, 2016 · 3 revisions

This is the interface to the pipeline builder. The builder takes information about the middleware you want to use in your application and the various routes you want to have through the OWIN pipeline and builds an OWIN pipeline where all middleware has its dependencies satisfied.

This sample is from one of the projects in the example usage solution.

    public void Configuration(IAppBuilder app)
    {
        var packageLocator = new PackageLocator().ProbeAllLoadedAssemblies();
        var ninject = new StandardKernel(new Module(packageLocator));
        var builder = ninject.Get<IBuilder>();

        builder.Register(ninject.Get<NotFoundError>());
        builder.Register(ninject.Get<PrintRequest>());
        builder.Register(ninject.Get<ReportExceptions>());
        builder.Register(ninject.Get<FormsIdentification>());
        builder.Register(ninject.Get<TemplatePageRendering>());
        builder.Register(ninject.Get<AllowEverythingAuthorization>());
        builder.Register(ninject.Get<InProcessSession>());

         app.UseBuilder(builder);
    }

In this very simple example we configure a Ninject IoC container then use it to obtain a concrete implementation of IBuilder. We then register our middleware with the builder, and finally use the builder to build our OWIN pipeline.

In this very simple example there is no routing, no application defined dependencies between the middleware, and all middleware runs with its default configuration. In a real application you would use a fluid extension method to specify these things when registering each middleware.

For example to specify that MiddlewareB depends on MiddlewareA we can configure them like this:

    public void Configuration(IAppBuilder app)
    {
        var packageLocator = new PackageLocator().ProbeBinFolderAssemblies();
        var ninject = new StandardKernel(new Module(packageLocator));
        var builder = ninject.Get<IBuilder>();

        builder.Register(ninject.Get<MiddlewareA>())
            .As("Middleware A");

        builder.Register(ninject.Get<MiddlewareB>())
            .As("Middleware B")
            .RunAfter("Middleware A");

        app.UseBuilder(builder);
    }

For example to specify that MyMiddleware must run after the middleware that implements IMiddleware<ISession> we can configure it like this:

    builder.Register(ninject.Get<MyMiddleware>())
        .As("My Middleware")
        .RunAfter<ISession>();

To provide a configuration for your middleware, you need a class that implements IConfiguration. There are a couple of implementations of IConfiguration in this solution. This interface is also very simple to implement yourself. Note that you can have multiple instances of the same middleware with different configurations, therefore you have to specify the path in the configuration hierarchy where the middleware should look for its configuration data.

By far the best configuration option is to use Urchin. The example below assumes that you registered an implementation of IConfiguration with Ninject. To register IConfiguration for Urchin with your IoC container you only have to install the Owin.Framework.Urchin Nuget package. If you do this the packageLocator will probe the assembly and register everything with IoC automatically.

    var configuration = ninject.Get<IConfiguration>();

    builder.Register(ninject.Get<MyMiddleware>())
        .As("My Middleware")
        .ConfigureWith(configuration, "/myApp/middleware/myMiddleware");

To configure multiple paths through the OWIN pipeline for different requests you need routes. This is an example:

using ExampleUsage.Middleware;
using Owin;
using OwinFramework.Builder;
using OwinFramework.Configuration;
using OwinFramework.Routing;
using OwinFramework.Utility;

namespace ExampleUsage
{
    /// <summary>
    /// This example demonstrates a a more complex scenario with routes and
    /// different authentication mechanisms for each route. The resulting
    /// OWIN pipeline will be built like this:
    /// 
    /// session --> aspx pages --ui---> /secure --secure--> forms auth -----> template rendering
    ///          |                  |                                      |
    ///          |                  --> not /secure --public---------------^
    ///          |
    ///          -> non aspx --api--> cert auth ----> REST service rendering
    /// 
    /// Try these URLs and look at the putput in the console window:
    ///   http://localhost:12345/test.aspx
    ///   http://localhost:12345/secure/test.aspx
    ///   http://localhost:12345/api/user/98765
    ///   http://localhost:12345/test.jpg
    ///   http://localhost:12345/api/test.jpg
    ///   http://localhost:12345/secure/test.jpg
    /// </summary>
    public class StartupRouting
    {
        public void Configuration(IAppBuilder app)
        {
            // This demonstrates how you would configure the builder without using IoC
            // There are other startup examples in this project that demonstrate the IoC version
            var dependencyGraphFactory = new DependencyGraphFactory();
            var segmenterFactory = new SegmenterFactory(dependencyGraphFactory);
            var builder = new Builder(dependencyGraphFactory, segmenterFactory);
            var configuration = new DefaultValueConfiguration();

            // Note that the middleware components below can be registerd with the builder
            // in any order. The builder will resolve dependencies and add middleware into 
            // the OWIN pipeline so that all dependencies are satisfied. If there are
            // circular dependencies an exception will be thrown.

            // This middleware is built to run at the front of the Owin pipeline
            // so not much more to set up here.
            builder.Register(new ReportExceptions());

            // Configure different 404 behaviours for different routes.
            // Note that NotFoundError middleware is built to run at the end of the Owin
            // pipeline after all other middleware. If no other middleware handled the 
            // request then it returns a 404 response.
            builder.Register(new NotFoundError())
                .As("apiNotFoundError")
                .RunOnRoute("api")
                .ConfigureWith(configuration, "/owin/notFound/api");

            builder.Register(new NotFoundError())
                .As("uiNotFoundError")
                .RunOnRoute("ui")
                .ConfigureWith(configuration, "/owin/notFound/ui");

            builder.Register(new NotFoundError())
                .As("staticFilesNotFoundError")
                .RunOnRoute("staticFiles")
                .ConfigureWith(configuration, "/owin/notFound/staticFiles");

            builder.Register(new NotFoundError())
                .As("invalidNotFoundError")
                .RunOnRoute("invalid")
                .ConfigureWith(configuration, "/owin/notFound/invalid");

            // This says that we want to use forms based identification, that
            // we will refer to it by the name 'loginId', and it will
            // only be configured for the 'secure' route. This also defines
            // the configureation mechanism and specifies where to get config
            // for this instance in the config file.
            builder.Register(new FormsIdentification())
                .As("loginId")
                .ConfigureWith(configuration, "/owin/auth/forms")
                .RunOnRoute("secure");

            // This says that we want to use certificate based identification, that
            // we will refer to it by the name 'certificateId'.
            builder.Register(new CertificateIdentification())
                .As("certificateId")
                .ConfigureWith(configuration, "/owin/auth/cert");

            // This specifies the mechanism we want to use to store session.
            // We don't need to specify anything else because each middleware knows
            // already whether it needs session or not and the builder will ensure
            // that session is included in the pipeline before anything that needs it.
            builder.Register(new InProcessSession())
                .ConfigureWith(configuration, "/owin/session");

            // This configures a routing element that will split the OWIN pipeline into
            // two routes. There is a 'ui' route that has forms based authentication and 
            // template based rendering. There is an 'api' route that has certifcate based
            // authentication and REST service rendering.
            // Since this router does not have any route dependencies it will run directly
            // off the incomming request.
            builder.Register(new Router(dependencyGraphFactory))
                .AddRoute("ui", context => context.Request.Path.Value.EndsWith(".aspx"))
                .AddRoute("staticFiles", context =>
                {
                    var path = context.Request.Path.Value;
                    var fileExtensionIndex = path.LastIndexOf('.');
                    if (fileExtensionIndex < 0) return false;

                    var fileExtension = path.Substring(fileExtensionIndex).ToLower();
                    if (fileExtension == ".html") return true;
                    if (fileExtension == ".css") return true;
                    if (fileExtension == ".js") return true;
                    if (fileExtension == ".jpg") return true;
                    if (fileExtension == ".png") return true;
                    return false;
                })
                .AddRoute("api", context => context.Request.Path.Value.StartsWith("/api/"))
                .AddRoute("invalid", context => true);

            // This configures another routing split that divides the 'ui' route into 
            // 'secure' and 'public' routes.
            builder.Register(new Router(dependencyGraphFactory))
                .AddRoute("secure", context => context.Request.Path.Value.StartsWith("/secure"))
                .AddRoute("public", context => true)
                .RunOnRoute("ui");

            // This specifies that we want to use the template page rendering
            // middleware and that it should run on both the "public" route and
            // the "secure" route. This creates a join bewteen the routes.
            builder.Register(new TemplatePageRendering())
                .RunOnRoute("public")
                .RunOnRoute("secure")
                .ConfigureWith(configuration, "/owin/templates");

            // This specifies that we want to use the REST service mapper on the 'api' route
            // and that it should run after the 'certificateId' middleware
            builder.Register(new RestServiceMapper())
                .RunAfter("certificateId")
                .RunOnRoute("api")
                .ConfigureWith(configuration, "/owin/rest");

            // This statement will add all of the middleware registered with the builder into
            // the OWIN pipeline. The builder will add middleware to the pipeline in an order
            // that ensures all dependencies are met.
            // The builder will also create splits in the OWIN pipeline where there are routing 
            // components configured, and joins where middleware has a dependency on multiple 
            // routes.
            // If you want to see exactly how the Owin pipeline got built, there is a 
            // PipelineVisualizer middleware in the OwinFramework.Middleware package that you
            // can add to your configuraton. This middleware will return an SVG vizualization
            // of the pipeline including configurations and analytics.
            app.UseBuilder(builder);

            // Anything that you do with the builder after this point will have no effect on
            // to Owin pipeline which has already been built.
        }
    }
}

Clone this wiki locally