Dependency Injection: Inject Your Dependencies, Period!

Reasons on why I prefer dependency injection over static accessors.
2014-11-18 12:39
Tugberk Ugurlu


There is a discussion going on inside ASP.NET/Logging repository whether we should have static Logger available everywhere or not. I am quite against it and I stated why with a few comments there but hopefully with this post, I will try to address why I think the dependency injection path is better for most of the cases.

Let’s take an example and explain it further based on that.

public class FooManager : IFooManager
{
    private readonly IClock _clock;
    private readonly ILogger _logger;
    private readonly IEnvironmentInfo _environmentInfo;

    public FooManager(IClock clock, ILogger logger, IEnvironmentInfo environmentInfo)
    {
        _clock = clock;
        _logger = logger;
        _environmentInfo = environmentInfo;
    }

    // ...
}

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:

image

In any other text editor:

image

Inside Visual Studio when I am writing tests:

Screenshot 2014-11-18 13.07.38

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:

public class FooManager : IFooManager
{
    public void Run()
    {
        if(DateTime.UtcNow > EnvironmentInfo.Instance.LicanceExpiresInUtc)
        {
            Logger.Instance.Log("Cannot run as licance has expired.");
        }

        // Do other stuff here...
    }
}

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:

image

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:

Screenshot 2014-11-18 14.17.13

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:

It is Still Bad Even If It is not Static

Yes, it’s still bad. Let me give you a hint: Service Locator Pattern.

Using "Ctrl+Enter, Enter" Instead of "Ctrl+., Enter" for C# Quick Actions on Visual Studio 2015 Preview

One of the new features of the Roslyn based code editor is Quick Actions. Let's see how you can use Ctlr+Enter, Enter combination instead of Ctrl+., Enter :)
2014-11-13 20:46
Tugberk Ugurlu


Visual Studio 2015 preview went public yesterday and we can enjoy the new Roslyn based code editor for C# and Visual Basic :) You can learn more about these new cool things about the code editor on Visual Studio blog.

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:

Screenshot 2014-11-13 22.14.49

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+."

Screenshot 2014-11-13 22.15.54

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:

Screenshot 2014-11-13 22.26.16

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

image

Search for "lineopenabove" command there which actually uses "Ctrl+ Enter" shortcut. Remove that by hitting "Remove" button:

image

Now, search for "quickaction" and apply the "Ctrl + Enter" shortcut as shown below:

vs-quickaction

Hoping that this will be the default at some day :) Happy "Ctrl+Enter, Enter"ing :)

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

Getting the Client’s IP Address in ASP.NET vNext Web Applications

I was wondering about how to get client’s IP address inside an ASP.NET vNext web application. It’s a little tricky than it should be but I finally figured it out :)
2014-10-30 10:04
Tugberk Ugurlu


I was wondering about how to get client’s IP address inside an ASP.NET vNext web application. It’s a little tricky than it should be but I finally figured it out. So, I decided to write it down here so that anyone else can see how it’s done right now.

BIG ASS CAUTION! At the time of this writing, I am using KRE 1.0.0-beta2-10648 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.

First thing to highlight here is "HTTP Features" feature (mouthful, I know :)). It’s a really exciting design if you ask me and basically, the HTTP server underneath your application will implement certain features and your application can work with these implementations. Some of the features that a server might implement can be found inside the Microsoft.AspNet.HttpFeature package. However, it’s not limited to these features only. You watch Chris Ross talking about HTTP Features on Web Camps TV to find out more about this as he gives a nice overview on HTTP Features design.

One of these HTTP features is HTTP connection feature (IHttpConnectionFeature if you want to be more specific). This feature is responsible for giving local and remote connection information for current request and this is where we can get client’s IP Address. You can try to get IHttpConnectionFeature from the HttpContext instance which you get per each request. HttpContext has two methods called GetFeature and one of them accepts a generic parameter. You can use this method to retrieve a specific feature you want to reach out to. The below Startup class shows you how you can get the client’s IP Address through the IHttpConnectionFeature.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.HttpFeature;

namespace RemoteIPAddressSample
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async (ctx) =>
            {
                IHttpConnectionFeature connection = ctx.GetFeature<IHttpConnectionFeature>();
                string ipAddress = connection != null
                    ? connection.RemoteIpAddress.ToString()
                    : null;

                await ctx.Response.WriteAsync("IP Address: " + ipAddress);
            });
        }
    }
}

When I hit the HTTP endpoint now, I’ll see my client’s IP address inside the response body:

image

We can even make this look nicer by refactoring this into an extension method.

public static class HttpContextExtensions
{
    public static string GetClientIPAddress(this HttpContext context)
    {
        if(context == null)
        {
            throw new ArgumentNullException("context");
        }

        IHttpConnectionFeature connection = context.GetFeature<IHttpConnectionFeature>();

        return connection != null
            ? connection.RemoteIpAddress.ToString()
            : null;
    }
}

Way better. We can now use this nice looking HttpContext extension instead:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async (ctx) =>
        {
            await ctx.Response.WriteAsync("IP Address: " + ctx.GetClientIPAddress());
        });
    }
}

One thing to mention here is that the HTTP server which your application is running on top of may choose not to implement this feature. It sounds like a very unreasonable situation as something this fundamental should be there all the time but it’s what it is. So, you should be always careful when reaching out to properties of this feature as you may get null values when you call GetFeature<T>. This rule probably applies most of the HTTP features but I wasn’t able to find any certain information whether there is a check at the very early stages of the pipeline to refuse to use the server if specific features are not implemented by the server. I’ll probably update the post when I find this out.

MSP Turkey Kickoff 2014 ASP.NET Web API and SignalR Presentation Slides, Recording and Links

I was at Microsoft Turkey office yesterday and I gave a presentation on ASP.NET Web API and SignalR in context of this year’s MSP Kickoff. This post covers where you can reach out to presentation slides, recording and several relevant links.
2014-10-19 13:44
Tugberk Ugurlu