This is a simple class whose job is not important in our context. The way I see this class inside Visual Studio is as below:

In any other text editor:

Inside Visual Studio when I am writing tests:

There are two things fundamental things why I would like this approach.

The Requirements of the Component is Exposed Clearly

When I look at this class inside any editor, I can say that this class cannot function properly without IClock, ILogger and IEnvironmentInfo implementation instances as there is no other constructor (preferably, I would also do null checks for constructor parameters but I skipped that to keep the example clean). Instead of the above implementation, imagine that I have the following one:

With this approach, we are relying on static instances of the components (and they are possibly thread-safe and singleton). What is wrong with this approach? I’m not sure what’s the general idea for this but here are my reasons.

First thing for me to do when I open up a C# code file inside visual studio is to press CTRL+M, O to get an idea about the component. It has been kind of an habit for me. Here how it looks like when I do that for this class:

I have no idea what this class needs to function properly. I have also no idea what type of environmental context it relies on. Please note that this issue is not that big of a problem for a class which is this simple but I imagine that your component will have a few other methods, possible other interface implementations, private fields, etc.

I Don’t Need to Look at the Implementation to See What It is Using

When I try to construct the class inside a test method in Visual Studio, I can super easily see what I need to supply to make this class function the way I want. If you are using another editor which doesn’t have a tooling support to show you constructor parameters, you are still safe as you would get compile errors if you don’t supply any required parameters. With the above static instance approach, however, you are on your own with this issue in my opinion. It doesn’t have any constructor parameters for you to easily see what it needs. It relies on static instances which are hard and dirty to mock. For me, it’s horrible to see a C# code written like that.

When you try to write a test against this class now, here is what it looks like if you are inside Visual Studio:

You have no idea what it needs. F12 and try to figure out what it needs by looking at the implementation and good luck with mocking the static read-only members and DateTime.Now :)

I’m intentionally skipping why you shouldn’t use DateTime.Now directly inside your library (even, the whole DateTime API). The reasons are variable depending on the context. However, here are a few further readings for you on this subject:

One of the new features is something ReSharper user are very familiar with: quick actions. Sometimes inside the editor, you will see a yellow lamp popping up:

This indicates that there are possible actions that you can take on this piece of code. You can bring up these actions by hitting "Ctrl+."

Later, you can chose the action from the list and apply it by hitting ENTER. For very obvious stuff like the above removing unused using sample, you want to apply the action instantly. If you are using ReSharper before, I’m 99.9% sure that you will find yourself hitting "Ctrl+., ." :) as it’s easier than moving your finger from "." key to "Enter" key :) Luckily, we can come with a better keyboard shortcut for this which is "Ctrl+Enter, Enter" :)

Inside Visual Studio, go to Tools > Options:

Search for keyboard and you will see the "Keyboard" section under "Environment" pane:

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.

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:

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):

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:

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.