StructureMap and MVC5 – Resolving the resolution exception for IUserStore

I’m currently working on an MVC5 website which uses StructureMap for Inversion of Control operations. Everything was working fine but then I started to get exceptions when I ran the application and attempted to login (not sure if Update 3 was responsible for surfacing this problem but it certainly worked without any problems previously)

Now, clicking ‘Continue’ in Visual Studio (or pressing F5) allowed the application to continue with no further issues but I wanted to get to the bottom of this issue – I certainly didn’t want this coming back at me when the site goes live.

Clicking on ‘View Detail’ I found the following error message which seemed surprisingly informative;

No default Instance is registered and cannot be automatically determined for type ‘IUserStore<ApplicationUser>’

There is no configuration specified for IUserStore<ApplicationUser>

1.) new ApplicationUserManager(*Default of IUserStore<ApplicationUser>*)
2.) MyDiveLogs.ApplicationUserManager
3.) Instance of MyDiveLogs.ApplicationUserManager
4.) new AccountController(*Default of ApplicationUserManager*, *Default of ApplicationSignInManager*)
5.) MyDiveLogs.Controllers.AccountController
6.) Instance of MyDiveLogs.Controllers.AccountController
7.) Container.GetInstance(MyDiveLogs.Controllers.AccountController)

So – what does that mean?

Well, in a nutshell it means that StructureMap could not determine how to create a concrete instance of IUserStore, which is required to create an ApplicationManager instance which is in turn required to create the AccountController.

This is caused by StructureMap being ‘greedy’ and will attempt to use the constructor with the most parameters. In the case of the AccountController it will ignore the parameterless constructor and try to use the one that requires an ApplicationUserManager (the root of my issue) and an ApplicationSignInManager.

Having trawled around the web trying to locate a resolution I’ve found a couple of options;

  • Tell StructureMap to use the parameterless constructor instead or
  • Tell StructureMap how to instantiate the instances correctly

The first option is a simple matter of adding an attribute to the AccountControllers parameterless constructor as below;

[DefaultConstructor]
public AccountController()
{
}

This works fine and if you are worried about how the AccountController will function without being given an ApplicationUserManager and ApplicationSignInManager to use then fret not – take a look at its UserManager and SignInManager properties. The getter will perform a null check and create the appropriate instance as required.

Interestingly, this helps us with the second option for resolving this problem, i.e. telling StructureMap how to create the instances for us.

Locate the IoC.cs class (mine was in a folder called DependancyResolution in the main MVC project) and update the Initialize method as below (note that you may have to import some namespaces)

public static IContainer Initialize() {
    return new Container(c =>
    {
        c.AddRegistry<DefaultRegistry>();

        // ADD THESE LINES
        c.For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>().Use<Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>>();
        c.For<System.Data.Entity.DbContext>().Use(() => new ApplicationDbContext());
        c.For<Microsoft.Owin.Security.IAuthenticationManager>().Use(() => HttpContext.Current.GetOwinContext().Authentication);

    });
}

And that’s it – you should now be able to access Actions within the AccountController without this exception being thrown.

Validating Start/End Dates with Fluent Validation for MVC 4

In my current contract I needed to add date filtering to a grid of search results in and MVC view – how hard could it be?
Well the filtering was the easy bit, validating the user input proved to be much more problematic. The view that I had contained, among other things, a couple of fields for Start and End Date where the user would select the dates using a jQuery date picker. I knew that I could rely on standard MVC validation to make sure that the user had entered a valid date, but how do I ensure that they have entered an End Date that falls AFTER the Start Date? This simple requirement is not something that can be acheived with the standard Data Annotation attributes but I was lucky as the project already had made use of the FluentValidation extension.

Creating a custom validator using FluentValidation is pretty simple as below:

public class SearchValidator: AbstractValidator
{
    public SearchValidator()
    {
        RuleFor(m => m.StartDate)
            .NotEmpty()
            .WithMessage("Start Date is Required");
 
        RuleFor(m => m.EndDate)
            .NotEmpty().WithMessage("End date is required")
            .GreaterThan(m => m.StartDate.Value)
                            .WithMessage("End date must after Start date")
            .When(m => m.StartDate.HasValue);
    }
}
This validation will ensure that the user has entered something in the Start Date (standard validation will ensure that the date is valid) and that an End Date has been entered and is later than that Start Date.

Wiring this up to the view model is a simple matter of adding an attribute to the class:

[Validator(typeof(SearchValidator))]
public class SearchViewModel
{
    public DateTime? StartDate { get; set; }
 
    public DateTime? EndDate { get; set; }
}
The final steps are to add the markup to display the resulting validation messages;

Start Date: @Html.EditorFor(m => m.StartDate)
@Html.ValidationMessageFor(m => m.StartDate)
 
 
End Date: @Html.EditorFor(m => m.EndDate)
@Html.ValidationMessageFor(m => m.EndDate)

and to ensure that the validation is triggered in the Action Method;


if (ModelState.IsValid)
{
    // do stuff and return the Search view
    return View("Search");
}
else
{
    // Validation has failed, return the same view with the model
    return View(model);
}
Now when the user clicks the Search button the validation will ensure that Start and End Dates are entered and that the End Date is later than the Start Date. What's more, will be applied on the ViewModel wherever it's used - you don't have repeated code in your action methods.

Discovering T4MVC – Replacing Literal Strings with Strongly Typed Helpers

One of the things I love about working as a contractor is getting exposure to technologies, tools and utilities that will improve my coding and help me produce better code – geeky but true.
My most recent contract is no exception and this time I’ve decided to share this little gem of an extension which will remove those pesky literal string from your MVC Views.

Any developer who has worked with MVC will have written code similar to the following:

@Html.ActionLink("Edit", "Edit", "Magazine", new { Id = Model.Id }, null)
This will create a simple "Edit" Hyperlink which is call the "Edit" action method on the "Magazine" controller passing an "Id" parameter and there's nothing wrong with it. But what if you change the name of the action method, or come to that, the controller itself? Imagine hunting down every instance of the of a string literal and changing it; possible yes but time consuming and can you be sure you got them all.

Enter T4MVC – a simple T4 Text Template which generates a new class within the project that provides strongly typed helpers that can be used in place of the string literals.

The extension can be installed via NuGET and will add a few files to the project, the most important of which is ‘T4MVC.tt’. By right-clicking on the file and selecting ‘Run Custom Tool’ the magic happens and a new helper class called ‘MVC’ is generated.

With the helper class generated the above code could now be written as follows:

@Html.ActionLink("Edit", MVC.Magazine.ActionNames.Edit, MVC.Magazine.Name, new {id = Model.Id}, null)
Notice how the action and controller names have been replaced with strongly typed string values.

Whenever you add, remove or change an action method (or a controller come to that) just right-click on the ‘T4MVC.tt’ file and run the custom tool to regenerate the helper class. If an action method had been renamed or removed then every instance of it being referenced as above would now cause a design-time compiler error which makes them super simple to locate and when the build succeeds you can be sure that you have no errant references to non-existent action methods.

Hopefully you will find this as useful as I did – I’ll be sure to include this in all my MVC projects from now on.

One drawback I found with using T4MVC was that I had to remember to regenerate the files each time I made a change to the controller methods, if I didn’t then I could get a compiler error – which is of course the point of the extension, but frustrating when you forget.

Well, help is at hand with another, zero configuration, Visual Studio extension called AutoT4MVC – which essentially triggers the regeneration whenever the project is built.
To install the extension just open up the NuGet manager and search for AutoT4MVC, install, restart Visual Studio and you’re off – no configuration and no face/palm when you forget to regenerate before building/debugging. Simple!