Today I came across somewhat annoying bug. On one of the sites I maintain, after enabling HTTPS users could not download files anymore. The annoying part was that I could. With all the browsers. They could not with IE9. Turned out that the issue was only on the internal network only over HTTPS: the same file was downloaded from the same address fine over HTTP, but when you go HTTPS on the same url, this happened:

Unable to download from HTTPS

Turned out that some domain policy was prohibiting to store encrypted files during browsing. IE has this setting Do not save encrypted pages to disk (Inside Tools / Internet Options > Advanced) that caused other people to complain. However in my situation this was not turned on which was strange. I decided to give a recommended trick with headers a go and it worked:

I have modified Cache-Control header to be no-store, no-cache and the problem went away. Strange!

Sometimes I have to configure sites that are no actually in my control, I only host and administer them. But site development/update is done by somebody else. Or it could be a PHP (yuck!) hosted on IIS.

Today I had to enable a bunch of sites to be served over HTTPS, all these sites sit under one IP, but under different subdomains. Unfortunately IIS does not have ability to configure from UI host header for HTTPS connections. So you have to drop down to command line:

appcmd set site /site.name:"<SiteName>" /+bindings.[protocol='https',bindingInformation='*:443:subdomain.domain.com']

And then in web.config add redirection to HTTPS, but make sure URL Rewrite is installed on server (check if %SystemRoot%\system32\inetsrv\rewrite.dll file is present):

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

And add STS header to all the requests:

<configuration>
    <system.webServer>
        <httpProtocol>
          <customHeaders>
            <remove name="X-Powered-By"/>
            <add name="Strict-Transport-Security" value="max-age=31536000"/>
          </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

Just writing down the steps for myself, so I don’t have to search this stuff over again in 6 months time.

As far as I know next version of ASP.Net is going to abandon MSBuild and build projects differently. Can’t wait for this to happen!

But for now we are still stuck with horribleness of XML and MSBuild (did I tell you I hate MSBUILD with passion?).

When I start a new MVC project, I add extra bits of MSBuild script into *.csproj file.

Missing Content files

First element is to fail a build if some of *.js or *.css files are missing from the project folder. This happened before – somebody in a team forgets to check-in a new file site.css – build server is silent for this matter. Only until somebody gets latest version of the project, builds, looks on it in a web-browser and notices that styles are not right, then the digging starts happening.

So here is the snippet to add to your project:

<Target Name="ValidateContentFiles">
    <Error Condition="!Exists(%(Content.FullPath))" Text="Missing Content file [%(Content.FullPath)]" />
</Target>

Simples – issue error if some of the “Content” files not on the hard-drive.

*.cshtml files marked as “None” for Build Action

This happened to me a few times now: to create a new view you copy-paste existing file, rename the file and change the internals. This is much faster than having to ask Visual Studio to create a new View file for you. The problem starts that sometimes files created this way are marked as “None” in Build Action (Right click on the file, Properties -> Build Action). This is very subtle change and not discoverable on development stage. But when you deploy the application to a server, files marked as None are not packed into the package. And your server now missing these view files. And only when somebody navigates to that missing page – that’s when you get a nasty exception in your face (hopefully your face, not your customer’s).

To avoid this Stackoverflow actually provided me very good answer (for a change).
So to fail a build on *.cshtml file being marked as None, add this snippet to your .csproj file

<Target Name="EnsureContentOnViews" BeforeTargets="BeforeBuild">
    <ItemGroup>
        <Filtered Include="@(None)" Condition="'%(Extension)' == '.cshtml'" />
    </ItemGroup>
    <Error Condition="'@(Filtered)'!=''" Code="CSHTML" File="$(MSBuildProjectDirectory)\%(Filtered.Identity)" Text="View is not set to [BuildAction:Content]" />
</Target>

I wish these were the default settings in the project template.

Some users still live in era of Windows 95 where you had to do double-click to make something happen. And this double-clicking goes with them when they go online. So they double-click on links, double click on submit buttons… Wait? did you just double-clicked that button? submitted the form twice? OOPS!

There are a lot of advice online how to stop this happening, but I have not found a complete solution. Here is my stub at this (using jQuery):

$('input:submit').click(function () {
    var button = this;
    var oldValue = button.value;
    setTimeout(function() {
        button.disabled = true;
        button.value = 'Working...';
        setTimeout(function() {
            button.disabled = false;
            button.value = oldValue;
        }, 500);
    }, 0);
});

What are we doing here? seems like too much code for a simple task. A lot of advice goes to e.preventDefault() but that stops the form submission. Some people recommend adding form.submit() after the preventing default action. That smells. What if I did not want to submit the form, but some other event was triggered on click? If you just disable the button on click – your form will not be submitted because disabled html elements are not submitted.

In this snippet I’m delaying button disabling. This gives a chance to other events to fire – I don’t need to submit the form manually. And inside that timeout I’m setting another delayed function to re-activate the function. Because in era where JavaScript is executed on servers (node.js, I’m looking at you!), it is just plain wrong not to do a validation on a client. So in case when the validation has failed, I re-enable the button again so user can re-submit.

I’ve tried that in latest (17 Dec 2014) Chrome and in IE9 in both cases works as expected. Let me know how this can be improved!

I’m a frequent user of RDP and sometimes you get stuck with within the same connection window and can’t get unstuck because the bar on top just does not come up. To make the bar come-down hit CTRL + ALT + HOME and to break free from the full-screen mode hit CTRL + ALT + BREAK

I’ll leave this here for my future reference.

The title is quite vague, but this is the best I can call this post. Bear with me, I’ll explain what I mean.

While working with Asp.Net MVC, in Razor views I use Html helpers a lot. My view end up looking like this:

@Html.TextBoxFor(m => m.Title)
@Html.TextAreaFor(m => m.Description)

And later if I write JavaScript and need to reference one of the input fields, I usually do this:

var title = document.getElementById("Title");
var description = document.getElementById("Description");

or if you use jQuery you go like this:

var title = $("#Title");
var description = $("#Description");

This is fine and works. Until you start renaming field names in your model. And then you need to track down where you hard-coded the input id. And many times these references slip away (they do from me!) and remain unchanged.

Would it not be great if these changed could be picked up automatically? or even better, do some sort of strongly-typed reference to the element if it is used in JavaScript?

Just use @Html.IdFor(m => m.Name)

And your JS code would look like this:

var title = document.getElementById("@Html.IdFor(m => m.Title)");
var description = $("#@Html.IdFor(m => m.Description)");

Below I’ve re-invented the wheel. [Facepalm]

So I trolled through MVC source code and figured out how it generates id’s for elements and here are my findings:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

public static class HtmlHelpers
{
    public static String ElementId<T, TResult>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TResult>> selector)
    {
        var text = System.Web.Mvc.ExpressionHelper.GetExpressionText(selector);
        var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(text);
        var id = TagBuilder.CreateSanitizedId(fullName);

        return id;
    }
}

As you can see, I have not made any custom code, all components are from MVC and are applied in the same order as MVC does when it generates id for elements when you call for @Html.EditorFor(). So this guarantees the provided id from this function will match the id in your form.

In the view you use it like this:

@Html.ElementId(m => m.Title)

And your JS code would look like this:

var title = document.getElementById("@Html.ElementId(m => m.Title)");
var description = document.getElementById("@Html.ElementId(m => m.Description)");

A bit of mouthful, but gives you the safety net of strong types. I have not actually used it widely, so not sure how it’ll work out in the longer run.

A note to myself, next time I try to do view compilation in msbulid and see exception

Can’t find the valid AspnetCompilerPath

I should either install VS2013 on my build server. Or choose a different version of msbuild.exe:
C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe.

The problem is caused by version mis-match. New msbuild is part of Visual Studio 2013 and not part of .Net framework itself. And by default your PATH variable points to .Net folders where older msbuild is found. So you in your scripts you need to explicitly specify what msbuild you need to use.

Part 1: AspNet Identity and IoC Container Registration

Sounds like I’m making a series of articles about ASP.Net Identity and how to use it with Depenency Injection. Part 1 have seen a lot of hits from Google in just a few days. I suppose it is worth extending the tutorial.

Building up on Part 1 where I wired all Identity components to be injected by Unity container, now I’m going to add emailing service for email confirmation and password reset.

My plan is to use SendGrid as a email service and email debugging service Mailtrap.IO as a hosted fake SMTP server.

EmailService Class

Standard VS template for ApplicationUserManager does not have an implementation for EmailService:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        return Task.FromResult(0);
    }
}

Let’s create one that uses SendGrid to send emails. Go to http://sendgrid.com/ and get registered: there is a free tier that allows you to send up to 200 emails a day. This is good enough for our testing. Make sure you put your details correctly – all accounts go through moderation before they are allowed to send out emails. And it took a few hours before my account got approved, I also had to reply their support saying that I’m a developer and will only use the account for testing and learning purposes.

Now go install SendGrid nuget package:

PM> Install-Package SendGrid 

Now take a careful look on IIdentityMessageService interface: it has only one method: Task SendAsync(IdentityMessage message). So what information does IdentityMessage contains?
By looking in decompiler I see this:

Identity Message

Basically it is a data container with no methods. We have strings available:

  • Destination – contains email address
  • Subject – email subject
  • Body – text of the email

Now let’s look on SendGrid documentation for C# client. I came up with this as an implementation for the email service:

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using SendGrid;


namespace IoCIdentity.Identity
{
    public class SendGridEmailService : IIdentityMessageService
    {
        public async Task SendAsync(IdentityMessage message)
        {
            // Create the email object first, then add the properties.
            var myMessage = new SendGridMessage();

            // this defines email and name of the sender
            myMessage.From = new MailAddress("no-reply@tech.trailmax.info", "My Awesome Admin");

            // set where we are sending the email
            myMessage.AddTo(message.Destination);

            myMessage.Subject = message.Subject;

            // make sure all your messages are formatted as HTML
            myMessage.Html = message.Body;

            // Create credentials, specifying your SendGrid username and password.
            var credentials = new NetworkCredential("SendGrid_Username", "SendGrid_Password");

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email.
            await transportWeb.DeliverAsync(myMessage);
        }
    }
}

I’ve renamed EmailService into SendGridEmailService because we are going to have 2 services: one for production, another for testing.

Now it is a time to register this service with DI Container. Open our old friend UnityConfig and add the following line:

// whenever object requires IIdentityMessageService dependency, give them SendGridEmailService
container.RegisterType<IIdentityMessageService, SendGridEmailService>();

Inject this service into ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService) : base(store)
    {
        this.EmailService = emailService;
        // the rest of configuration
    }
}

Change AccountController to send out email confirmations on user registration:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await signInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                string code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await userManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

All of this is unmodified template code. All I had to do is to uncomment 3 lines related to userManager.SendEmailAsync() and make sure names match.

And now it is a time to test! Hit F5 to start debugging your site, this should launch your web-application. Go to register page, fill in your email, put a password and watch magic. Once you’ve done the registration, you should receive email from your own service! But beware, I got my confirmation email going to spam box in Gmail. Oops!

Check your spam inbox!

Click on link in the email and this should bring you back to your site to email confirmation page /Account/ConfirmEmail.

Now you can stop there: you have your email confirmation sent out and email service class is injected. But the fun only starts!

Fake SMTP Server

When testing account registration, and if you send emails to your real inboxes, you will run out of addresses pretty fast. I’ve got like 5 accounts, but I’d like to try registration process many more times than that. Also I don’t want to worry about sending an email to a real email address, in case I send it to somebody else, not just myself (I’ve done it in the past!).

I have written about Mailtrap.io before and this is another chance to mention this awesome service and how to hook it into your development cycle.

What is Mailtrap.io

Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers.

I think this sums up pretty well. I’ll add that there is a pile of fake SMTP servers you can install locally. But I have not seen hosted solutions (other than Mailtrap). When working ina team, centralised, install-free and configuration-free solution works best. Think of a new developer in the team – he/she gets a source code from your version control, hit F5 and up and running with the project. No need to configure fake SMTP server locally.

Now head to Mailtrap.io and get registered. There is a free tier that is just perfect for our small experiment (don’t you love the free tiers in services?).

Anyway, enough blah, more code!

To use Mailtrap service, we need to implement IIdentityMessageService. Mailtrap is quite good with documentation and it already provides a “hello world” sample on many programming languages, including C#:

Hello World for Mailtrap

I’ll use that code as a starting point for our implementation:

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;


namespace IoCIdentity.Identity
{
    public class MailtrapEmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
        var client = new SmtpClient
        {
            Host = "mailtrap.io",
            Port = 2525,
            Credentials = new NetworkCredential("24077a300d1d0a919", "36ac3619e3c015"),
            EnableSsl = true,
        };

        var @from = new MailAddress("no-reply@tech.trailmax.info", "My Awesome Admin");
        var to = new MailAddress(message.Destination);

        var mail = new MailMessage(@from, to)
        {
            Subject = message.Subject,
            Body = message.Body,
            IsBodyHtml = true,
        };

        client.Send(mail);

        return Task.FromResult(0);
        }
    }
}

To try it out, I’ll replace what type Unity is injecting as IIdentityMessageService:
Previous line container.RegisterType<IIdentityMessageService, SendGridEmailService>();
Now becomes container.RegisterType<IIdentityMessageService, MailtrapEmailService>();

Start the application and try to register the user: watch your Mailtrap inbox receive first intercepted email:

Send to what email address???

That is pretty cool. You can give a random email address on the registration and only you will see the email, it won’t go anywhere further than the fake inbox. There is an option to redirect all incoming fake emails, but I have not found the use case for this yet.

Inject Different Classes in Dev and Prod

Now we have 2 different implementations of email service that can be used in Identity Framework. I would like to configure our DI container to use the implementation most appropriate to the case. If we are in production, use SendgridEmailService. If we are testing or developing use MailtrapUserService.

I find the problem of deciding if we are in production or in testing pretty hard. Given that code on developers machines are usually executed in Debug mode, we can easily check for that. But when it comes to Testing environment, it is usually used by QA people (or sometimes clients) and is not running in Debug mode. Ideally Testing environment is identical to production, so there is not many “in-code flags” that we can use.
In the past I have added a setting in web.config/appSettings: <add key="isProduction" value="false" /> and checked for this setting. For production, this setting was changed during the deployment pipeline (web.config transformation).

But for the purposes of our little tutorial, we can rely on checking if the code is in Debug mode or if the request is local to the server where it is hosted. Here is the registration part:

container.RegisterType<IIdentityMessageService, SendGridEmailService>("production");
container.RegisterType<IIdentityMessageService, MailtrapEmailService>("debugging");

container.RegisterType<IIdentityMessageService>(new InjectionFactory(c =>
    {
        try
        {
            // not in debug mode and not local request => we are in production
            if (!HttpContext.Current.IsDebuggingEnabled && !HttpContext.Current.Request.IsLocal)
            {
                return c.Resolve<IIdentityMessageService>("production");
            }
        }
        catch (Exception)
        {
            // Catching exceptions for cases if there is no Http request available
        }
        return c.Resolve<IIdentityMessageService>("debugging");
    }));

Now this looks scary. Let’s talk through each bit separately. This line:

container.RegisterType<IIdentityMessageService, SendGridEmailService>("production");

is telling the container to register type SendGridEmailService as an implementation for interface IIdentityMessageService and add named key to this registration as “production”. Pretty much the same happens on the next line about MailtrapEmailService, only the registration key is “debugging”. Basically this is some sort of alias for the registration. This works for the cases when we have more than one implementation class registered for one interface, just as we have at the moment.

Registration for IIdentityMessageService with InjectionFactory is the place where we decide which of the implementations to go for. I check if we are running not in debug and http request is not local, then it is production code and we need SendgridEmailService, otherwise we need MailtrapEmailService. I do wrap checking for conditions into try/catch block: Http.Current will throw exceptions in cases when no http request is available (this can happen if you for some reason try to execute this code in Application_Start()).

I do resolution of concrete implementations through container and named resolution:

return c.Resolve<IIdentityMessageService>("production");

This call matches provided key "production" to previous registrations for the requested interface IIdentityMessageService with this key, and SendgridEmailService should be resolved.

Instead of named resolutions I could have created concrete classes:

return new SendgridEmailService();

But if these classes evolve and dependencies are introduced (e.g. ILoggingService is injected), we will need to go back to this code and add dependencies. If we do resolution from the container, it will take care of the dependencies, as long as they are all registered.

Resetting Password Through Email

So far I’ve been getting an email only on user registration. But I could not reset the password. Let’s fix this to complete our solution.

AccountController already has all the stuff required for password resetting. All you need to do is uncomment some code:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await userManager.FindByNameAsync(model.Email);
        if (user == null || !(await userManager.IsEmailConfirmedAsync(user.Id)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }

        // Send an email with this link
        var code = await userManager.GeneratePasswordResetTokenAsync(user.Id);
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
        await userManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And add the link to this action from login page Login.cshtml:

<p>
    @Html.ActionLink("Reset password", "ForgotPassword")
</p>

That’s it – go try reset your password for the accounts you already created – all password reset passwords should go through to Mailtrap.

Give Me The Codez!

Here is the the full source code based on Part 1 and added code above

P.S. I’m struggling what should the next article in the series should be. I’m thinking 2FA and send out SMS, but there won’t be much DI happening there? Please suggest in comments.

I’m reading a lot of blogs about development and .Net. One of the blogs I read is from Jimmy Bogard and one of the recent posts there is about guidelines for using Dependency Injection container.

I got involved in comments and one of the commenters was suggesting using Func<IFoo> as injection instead of injecting the instance for IFoo. And reasons for that were:

  1. The “captive dependency” problem… objects with more constrained lifetime being held by objects with longer->lived lifetime.

  2. The (wasteful) big-bang object graph problem… when an MVC action only requires 1 dependency, but the dependency graph for all dependencies within the controller need to be resolved.

  3. The occasional property injection… when its 2am and I don’t feel like fixing a circular dependency issue (don’t hate).

And a follow up comment:

If you have circular dependencies, you aren’t immediately evaluating the circular path

I’d like to address this first, as it bothers me very much myself. It is best recommended to avoid circular dependency and it is entirely possible (I have not yet came across the situation where code could not be refactored out of that). In classical DI you’d fix circular dependency with property injection. Let’s try to fix this problem with injection of a function.

Here is a simple situation with classes:

public interface IBar
{
    void DoBar();
}

public class Bar : IBar
{
    private readonly Func<IFoo> fooFunc;

    public Bar(Func<IFoo> fooFunc)
    {
        this.fooFunc = fooFunc;
    }


    public void DoBar()
    {
        var foo = fooFunc.Invoke();
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

And Foo class:

public interface IFoo
{
    void DoFoo();
}

public class Foo : IFoo
{
    private readonly Func<IBar> barFunc;

    public Foo(Func<IBar> barFunc)
    {
        this.barFunc = barFunc;
    }


    public void DoFoo()
    {
        var bar = barFunc.Invoke();
        bar.DoBar();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Foo.DoFoo");
    }
}

Foo depends on IBar and Bar depends on IFoo. Simple circular dependency with proposed injection of functions that resolve actual class entities.

Let’s see how we can create instance of Foo and instance of Bar

Func<IBar> barFunc = () => new Bar(???);

Func<IFoo> fooFunc = () => new Foo(barFunc);

We still have circular dependency, because we can’t create a function to resolve IBar without function that resolves IFoo first.

Ok, so no what? Let’s try to have one of the objects depend on function and another on an interface:

public class Bar : IBar
{
    private readonly IFoo foo;

    public Bar(IFoo foo)
    {
        this.foo = foo;
    }


    public void DoBar()
    {
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

And Foo class is unchanged. And try to resolve both of the objects:

Func<IBar> barFunc = () => new Bar(new Foo(???));

Func<IFoo> fooFunc = () => new Foo(barFunc);

We still are in the same situation. We can’t resolve new instance of Bar because we can’t have Foo.

Another attempt – let’s do property injection:

public class Bar : IBar
{
    public Func<IFoo> FooFunc { get; set; }

    public Bar()
    {
    }

    public void DoBar()
    {
        var foo = FooFunc.Invoke();
        foo.DoFoo();

        Thread.Sleep(1000);
        Console.WriteLine("Executing Bar.DoBar");
    }
}

Now we are talking:

Func<IBar> barFunc = () => new Bar();

Func<IFoo> fooFunc = () => new Foo(barFunc);

var foo = fooFunc.Invoke();
var bar = new Bar()
                {
                    FooFunc = fooFunc,
                };

bar.DoBar();

The only problem that we still have circular dependency, only run-time, rather than compile time. See if you can figure out why it happens (just try running the code)! I’ve created a gist with full code I’ve tried running. Functions are unwrapped from lambdas, so you can set breakpoints and step into them while debugging.


Now, see if you notice a great big deception I’ve given you here. The dependency is very circular on functional level: DoBar() calls DoFoo() calls DoBar() calls DoFoo(), etc. It is impossible to run these functions: it is an infinite recursion/loop/whatever. And not type of wiring up will help you out. You’ll need to remove one of the function invocations from the classes:

public void DoFoo()
{
    Thread.Sleep(1000);
    Console.WriteLine("Executing Foo.DoFoo");
}

Now you can run the sample and it won’t explode with a series of exceptions. But our object wiring looks complex and is not much different from direct injection coupled with property injection of an object:

public class Bar : IBar
{
    public IFoo Foo { get; set; }

    public Bar()
    {
    }

    public void DoBar()
    {
        if (Foo == null)
        {
            throw new Exception("Foo property is not populated");
        }

        Foo.DoFoo();

        Console.WriteLine("Executing Foo.DoFoo");
    }
}


public class Foo : IFoo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        this.bar = bar;
    }

    public void DoFoo()
    {
        Thread.Sleep(1000);
        Console.WriteLine("Executing Foo.DoFoo");
    }
}

Wiring up and execution looks like this:

var bar = new Bar();
var foo = new Foo(bar);
bar.Foo = foo;

foo.DoFoo();
bar.DoBar();

The second version looks much more simple than the version with functions

Containers and function injection

In the same discussion I said that containers are not geared toward injection of functions. Well, yes, you can totally do this (Autofac):

var builder = new ContainerBuilder();
Func<IBar> barFunc = () => new Bar();

builder.RegisterInstance(barFunc);
builder.RegisterType<Foo>().As<IFoo>();
var container = builder.Build();

var foo = container.Resolve<IFoo>();
foo.DoFoo();

And it will work (given that Foo constructor takes Func<IBar>). But with given registration you can’t resolve Bar because it is not registered – we only registered Func<IBar>, but not IBar.

And I’m not aware of the way to register Func<IBar> together with IBar in one go, making it double-effort. Also imagine I have hundreds on ICommandHandler<TCommand> classes and hundreds of IQueryHandler<TQuery, TResult>. How can you register that with functions? Add a few decorators on top of that.

Probably one can come up with clever methods to do it, but that’ll be an addition to containers, not built-in functionality. And this is what I called “containers are not geared towards”.

Conclusion

However interesting this idea might seem like, I’ll stick to the classical DI with classes depending on interfaces. And all the issues discussed can be avoided by mostly following SOLID principles; no circular dependency; no massive graphs of objects; object resolution should be cheap and simple. To avoid captive dependency use Decoraptors.

Warning: If you have no idea what Dependency Injection is or you don’t know why you need this, don’t waste your time on this article. This approach is not recommended for cases when you don’t need a IoC container and have only a handful of controllers. Visual Studio 2013 template with Identity framework installed works perfectly out of the box. You’ll need minor changes to controllers and implement your EmailService, but you don’t need DI to enjoy full power of Asp.Net Identity framework. This article does not explain what DI is, how it works and why you need it. So proceed with caution and only if you know the difference between constructor injection and lifetime scope.

TL;DR: Registration code for Autofac, for SimpleInjector, for Unity.

Part 2: Sending Emails in Asp.Net Identity using Dependency Injection, Sendgrid and debugging it with Mailtrap.io

I regularly monitor StackOverflow for questions related to AspNet Identity framework. And one question keeps popping up over and over again: how do you use Inversion of Control containers with this framework.

If you know the main principles of Dependency Injection, things are very simple. Identity is very DI-friendly and I’ve done a number of projects with Identity and injected all Identity components via Autofac or SimpleInjector. The principles behind DI are applicable to all the containers, despite the differences in API’s for registration.

For the sake of this blog-post I’ll start with the standard VS2013 template and use Unity container, just because I’ve never used Unity before. You can view registrations for SimpleInjector in my test-project.

Projects where I used Autofac are far too complex to show as an example and none of them are open-source, so Autofac fans will have to figure out themselves from my examples.

Create project, install dependencies

For this sample I’ve used standard MVC project template from Visual Studio 2013.

First thing I’ve done – updated all Nuget packages. Just to keep new project really up to date.

Next thing I do is install container nuget packages:

PM> Install-Package Unity.Mvc 

In default template I don’t like the way Identity classes are all in one file and in App_Start folder, so I move them to /Identity folder and place a separate classes into separate folders. This is my preference, not really a requirement -) (Did you know with Reshrper you can place caret on class name and Ctr+R+O -> Move To Folder and get all the classes into separate files, into different folder)

Configure DI

Now, once we have installed Unity, let’s register components with it. I see that Unity nuget package have created 2 files for me in /App_Start: UnityConfig.cs and UnityMvcActivator.cs.

UnityConfig.cs looks like this (I’ve removed comments):

public class UnityConfig
{
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
        // TODO: Register your types here
        // container.RegisterType<IProductRepository, ProductRepository>();
    }
}

This is pretty standard class most containers have for registration, but I’ve never seen Lazy initialisation of the container before. I’ll keep it that way – when in Rome, do as Romans -) However I’ve got strong feeling that RegisterType method should be private, as it makes no sense to expose it to the world. And here the registrations of components should go. I’ll come back to this class later.

Now I’d like to have a look on another unity class UnityWebActivator:

using System.Linq;
using System.Web.Mvc;
using IoCIdentity;
using Microsoft.Practices.Unity.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]

namespace IoCIdentity
{
    public static class UnityWebActivator
    {
        public static void Start() 
        {
            var container = UnityConfig.GetConfiguredContainer();

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }
}

I’ve included namespaces and attribute, as these are pretty important here. The two assembly attributes come from WebActivator project and tells the application to execute methods before application starts and on application shut-down.

Start() method calls to the GetConfiguredContainer() from UnityConfig class that we’ve seen earlier – this is just initiates the DI container with registered types.
Next two lines de-register standard MVC filter instead registers Unity filter provider. I presume this is to enable injections into filter objects.

This line

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Sets Unity container as MVC standard dependency resolver, so in your static methods you can go DependencyResolver.Current.GetService<MyService>(); and this way Unity will be called into action and will resolve an instance of type MyService.

I think this is good enough initialisation code. Let’s move on.

Register components

Now let’s register components we need. Despite the fact, that Unity can resolve concrete types without registration (as per comments I’ve deleted), I’ll register them anyway. Here is the basic list of registrations I have. This is not a complete list, I’ll add more types there when I need them:

private static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<ApplicationDbContext>();
    container.RegisterType<ApplicationSignInManager>();
    container.RegisterType<ApplicationUserManager>();
}

Now, lets look on end consumers of our components – controllers. I’m starting with AccountController as it has a use of UserManager and ApplicationSignInManager. By default it looks like this:

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    private ApplicationSignInManager _signInManager;

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set { _signInManager = value; }
    }


    // this is hidden on the very bottom - go find it and delete later
    private IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }



// list of actions

Let’s follow the DI principles and remove all the crap. HttpContext.GetOwinContext().Get<ApplicationUserManager>() is a prime example of service locator as an anti-pattern. Also this does not use our Unity container, this uses Owin for object resolution. We don’t want to mix Owin registrations with Unity registrations for many reasons (the biggest reason is lack of lifetime management between 2 containers). So now my AccountController looks like this:

private readonly ApplicationUserManager userManager;
private readonly ApplicationSignInManager signInManager;
private readonly IAuthenticationManager authenticationManager;

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager)
{
    this.userManager = userManager;
    this.signInManager = signInManager;
    this.authenticationManager = authenticationManager;
}

// actions

If you noticed, previously we have not registered IAuthenticationManager with the container. Let’s do this now:

container.RegisterType<IAuthenticationManager>(
    new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

If you run your application now, you’ll get exception that “IUserStore can’t be constructed” – that is correct, we have not registered it anywhere and it is required for ApplicationUserManager. Register now IUserStore:

container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
            new InjectionConstructor(typeof(ApplicationDbContext)));

I specify what type I’d like to use as a parameter, otherwise Unity will try to resolve DbContext which is wrong. But instead we need our ApplicationDbContext.

ApplicationUserManager class

Now let’s look on UserManager class. The constructor does not have much in it, only takes IUserManager. But there is static method Create that creates an instance of UserManager and configures the settings:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    // configuration stuff here
}

This method creates instances of ApplicationUserManager. Let’s copy all the code from Create method into constructor:

public ApplicationUserManager(IUserStore<ApplicationUser> store, IdentityFactoryOptions<ApplicationUserManager> options)
        : base(store)
    {
        // Configure validation logic for usernames
        this.UserValidator = new UserValidator<ApplicationUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        this.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configure user lockout defaults
        this.UserLockoutEnabledByDefault = true;
        this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        this.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        this.EmailService = new EmailService();
        this.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;

        if (dataProtectionProvider != null)
        {
            this.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
    }

Now we have constructor parameter IdentityFactoryOptions<ApplicationUserManager> options. Previously this was supplied by Owin when we executed this code:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

This GetUserManager does magic tricks (I tried following their source code, but I’m not brainy enough-) and adds parameter you see above. But we’d like to avoid registration through Owin.

IdentityFactoryOptions<ApplicationUserManager> provides IDataProtectionProvider needed to generate user tokens to confirm account registration and for password reset tokens. It is used in constructor like this:

var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
    IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}

We can’t resolve ourselves IdentityFactoryOptions, we need Owin for that. And we can’t resolve IDataProtector ourselves as well. But after looking on source code of Owin I have found where this dataProtector is coming from: IAppBuilder.GetDataProtectionProvider(). But IAppBuilder is not available anywhere apart from Startup.Auth.cs file. So we can resolve this class where we can and save as static reference. And then use this reference where needed:

public partial class Startup
{
    // add this static variable
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        // add this assignment
        DataProtectionProvider = app.GetDataProtectionProvider();

        // other stuff goes here unchanged
    }
}

and in ApplicationUserManager I rewrite part with assigning UserTokenProvider like this:

// here we reuse the earlier assigned static variable instead of 
var dataProtectionProvider = Startup.DataProtectionProvider;

// this is unchanged
if (dataProtectionProvider != null)
{
    IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

    this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}

Now we can remove dependency of IdentityFactoryOptions<ApplicationUserManager> from ApplicationUserManager constructor. And the whole class now looks like this:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
    {
        // Configure validation logic for usernames
        this.UserValidator = new UserValidator<ApplicationUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        this.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configure user lockout defaults
        this.UserLockoutEnabledByDefault = true;
        this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        this.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        this.EmailService = new EmailService();
        this.SmsService = new SmsService();

        var dataProtectionProvider = Startup.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");

            this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
        }
    }
}

At this point the application should be usable and you should be able to register as a user, login and log out.

Clean-Up

Now that our app works with DI, let’s clean up some static calls that we don’t want around.

First of all, let’s fix ManageController, remove all empty controllers and initialisation of UserManager from OwinContext. The constructor should look like this:

private readonly ApplicationUserManager userManager;
private readonly IAuthenticationManager authenticationManager;

public ManageController(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
{
    this.userManager = userManager;
    this.authenticationManager = authenticationManager;
}

Now let’s go into Startup.Auth.cs and look on bits we don’t want:

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

I for sure know that Identity resolves ApplicationUserManager through Owin context and it uses it in certain cases. All the other Owin-resolved objects can be removed from this list:

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

Then remove static object creation for UserManager and SignInManager to Unity resolution:

app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

And remove static methods ApplicationUserManager.Create and ApplicationSignInManager.Create – no longer needed or used anywhere.

By now you should have all Identity components injected into your controllers via Unity container. I was able to register and login into the application. So the goal of this article is complete.

For your reference full source code of the solution is available on GitHub