Exciting Things About ASP.NET vNext Series: Middlewares and Per Request Dependency Injection

From the very first day of ASP.NET vNext, per request dependencies feature is a first class citizen inside the pipeline. In this post, I'd like to show you how you can use this feature inside your middlewares.
2014-11-09 21:20
Tugberk Ugurlu


Web development experience with .NET has never seen a drastic change like this since its birth day. Yes, I’m talking about ASP.NET vNext :) I have been putting my toes into this water for a while now and a few weeks ago, I started a new blog post series about ASP.NET vNext. To be more specific, I’m planning on writing about the things I am actually excited about this new cloud optimized (TM) runtime. Those things could be anything which will come from ASP.NET GitHub account: things I like about the development process, Visual Studio tooling experience for ASP.NET vNext, bowels of this new runtime, tiny little things about the frameworks like MVC, Identity, Entity Framework.

Today,  I would like to show you one of my favorite features in ASP.NET vNext: per-request dependencies.

BIG ASS CAUTION! At the time of this writing, I am using KRE 1.0.0-beta2-10679 version. As things are moving really fast in this new world, it’s very likely that the things explained here will have been changed as you read this post. So, be aware of this and try to explore the things that are changed to figure out what are the corresponding new things.

Also, inside this post I am referencing a lot of things from ASP.NET GitHub repositories. In order to be sure that the links won’t break in the future, I’m actually referring them by getting permanent links to the files on GitHub. So, these links are actually referring the files from the latest commit at the time of this writing and they have a potential to be changed, too. Read the "Getting permanent links to files" post to figure what this actually is.

If you follow my blog, you probably know that I have written about OWIN and dependency injection before. I also have a little library called DotNetDoodle.Owin.Dependencies which acts as an IoC container adapter into OWIN pipeline. One of the basic ideas with that library is to be able to reach out to a service provider and get required services inside your middleware. Agree or disagree, you will sometimes need external dependency inside your middleware :) and some of those dependencies will need to be constructed per each request separately and disposed at the end of that request. This is a very common approach and nearly all .NET IoC containers has a concept of per-request lifetime for ASP.NET MVC, ASP.NET Web API and possibly for other web frameworks like FubuMVC

From the very first day of ASP.NET vNext, per request dependencies feature is a first class citizen inside the pipeline. There are a few ways to work with per request dependencies and I’ll show you two of the ways that you can take advantage of inside your middleware.

Basics

For you ASP.NET vNext web application, you would register your services using one of the overloads of UseServices extension method on IApplicationBuilder. Using this extension method, you are registering your services and adding the ContainerMiddlware into the middleware pipeline. ContainerMiddlware is responsible for creating you a dependency scope behind the scenes and any dependency you register using the AddScoped method (in other words, any dependency which is marked with LifecycleKind.Scoped) on the IServiceCollection implementation will end up being a per-request dependency (of course it depends how you use it). The following code is a sample of how you would register your dependencies inside your Startup class:

public void Configure(IApplicationBuilder app)
{
    app.UseServices(services =>
    {
        services.AddScoped<IFarticusRepository, InMemoryFarticusRepository>();
        services.AddTransient<IConfigureOptions<FarticusOptions>, FarticusOptionsSetup>();
    });

    app.UseMiddleware<FarticusMiddleware>();
}

The way you reach out to per-request dependencies also vary and we will go through this topic in a few words later but for now, we should know that request dependencies are hanging off of HttpContext.RequestServices property.

Per-request Dependencies Inside a Middleware (Wrong Way)

Inside the above dependency registration sample code snippet, I also registered FarticusMiddleware which hijacks all the requests coming to the web server and well..., farts :) FarticusMiddleware is actually very ignorant and it doesn’t know what to say when it farts. So, it gets the fart message from an external service: an IFarticusRepository implementation. IFarticusRepository implementation can depend on other services to do some I/O to get a random message and those services might be constructed per request lifecycle. So, FarticusMiddleware needs to be aware of this fact and consume the service in this manner. You can see the implementation of this middleware below (trimmed-down version):

public class FarticusMiddleware
{
    private readonly FarticusOptions _options;

    public FarticusMiddleware(
        RequestDelegate next, IOptions<FarticusOptions> options)
    {
        _options = options.Options;
    }

    public async Task Invoke(HttpContext context)
    {
        IFarticusRepository repository = context
            .RequestServices
            .GetService(typeof(IFarticusRepository)) as IFarticusRepository;

        if(repository == null)
        {
            throw new InvalidOperationException(
                "IFarticusRepository is not available.");
        }

        var builder = new StringBuilder();
        builder.Append("<div><strong>Farting...</strong></div>");
        for(int i = 0; i < _options.NumberOfMessages; i++)
        {
            string message = await repository.GetFartMessageAsync();
            builder.AppendFormat("<div>{0}</div>", message);
        }

        context.Response.ContentType = "text/html";
        await context.Response.WriteAsync(builder.ToString());
    }
}

So, look at what we are doing here:

  • We are getting the IOptions<FarticusOptions> implementation through the middleware constructor which is constructed per-pipeline instance which basically means per application lifetime.
  • When the Invoke method is called per each request, we reach out to HttpContext.RequestServices and try to retrieve the IFarticusRepository from there.
  • When we have the IFarticusRepository implementation, we are creating the response message and writing it to the response stream.

The only problem here is that we are being friends with the notorious service locator pattern inside our application code which is pretty bad. Invoke method tries to resolved the dependency itself through the RequestServices property. Imagine that you would like to write unit tests for this code. At that time, you need know about the implementation of the Invoke method here to write unit tests against it because there is no other way for you to know that this method relies on IFarticusRepository.

Per-request Dependencies Inside a Middleware (Correct Way)

I was talking to a few ASP.NET team members if it was possible to inject per-request dependencies into Invoke method of my middleware. A few thoughts, Louis DeJardin sent a pull request to enable this feature in a very simple and easy way. If you register your middleware using the UseMiddleware extension method on IApplicationBuilder, it checks whether you are expecting any other parameters through the Invoke method rather than an HttpContext instance and inject those if you have any. This new behavior allows us to change the above Invoke method with the below one:

public async Task Invoke(HttpContext context, IFarticusRepository repository)
{
    if(repository == null)
    {
        throw new InvalidOperationException("IFarticusRepository is not available.");
    }

    var builder = new StringBuilder();
    builder.Append("<div><strong>Farting...</strong></div>");
    for(int i = 0; i < _options.NumberOfMessages; i++)
    {
        string message = await repository.GetFartMessageAsync();
        builder.AppendFormat("<div>{0}</div>", message);
    }

    context.Response.ContentType = "text/html";
    await context.Response.WriteAsync(builder.ToString());
}

Nice and very clean! It’s now very obvious that the Invoke method relies on IFarticusRepository. You can find the sample application I referred here under my GitHub account. When you run the application and send an HTTP request to localhost:5001, you will see the log which shows you when the instances are created and disposed:

I am still adding new things to this sample and it's possible that the code is changed when you read this post. However, here is latest state of the sample application at the time of this writing.

image



Comments

Michael
by Michael on Tuesday, Nov 11 2014 10:21:36 +00:00
Hi! Have you ever seen the error message: "Unable to resolve dependency Microsoft.AspNet.Abstractions." I've spent hours struggling with this issue. Orz
Tugberk
by Tugberk on Tuesday, Nov 11 2014 14:05:24 +00:00
@Michael I think you need to update your KRE and run restore again. Run "kvm upgrade" first and "kpm restore" for your application. Microsoft.AspNet.Abstractions was an old library as far as I know and it is now Microsoft.AspNet.Http.
Michael
by Michael on Wednesday, Nov 12 2014 10:23:25 +00:00
Thank you Tugberk! I'll give it a try.
Robin Sedlaczek
by Robin Sedlaczek on Tuesday, Dec 16 2014 08:47:54 +00:00
Very nice article! Thanks for writing it down! Please let me show you my article about DI in ASP.NET vNext: http://robinsedlaczek.wordpress.com/2014/11/22/dependency-injection-in-asp-net-vnext/
zapya
by zapya on Tuesday, Oct 25 2016 11:33:30 +00:00
Download Zapya for PC to share files and folders easily from PC to other devices

Tags