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

Tony Mackay has an alternative walk-through of a very similar process but with Autofac

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

Warning: If you don’t know 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 template with Identity framework works great out of the box. You don’t need DI to enjoy full power of Asp.Net Identity. 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.

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

  • Derek Flenniken

    Thanks! I was nearly there, but this was really helpful. For the Autofac fans:

    https://gist.github.com/3nth/5239a85d3e58511092a6

    • Great! Added your gist to list of links on the top.

  • ardalis

    Why aren’t you DI-ing EmailService and SmsService in ApplicationUserManager?

    • 1. I’m lazy
      2. I’m not implementing them, so no point in having them injected
      3. Solution is incomplete
      Pick one, or two, or three -)

      Honestly, I’ve started doing it, but abandoned because saw no point in doing it at this moment. My thoughts was that if you start implementing EmailService/SmsService and they have dependency, chances that you know what you are doing are high and you don’t need this article.

      • ardalis

        I ask not to be critical, but because it’s causing me problems. I have the Identity classes pulled out of my Web project into an Infrastructure project, and since ApplicationUserManager doesn’t (at least for now) know about my container nor expect an email service as a constructor dependency, it’s difficult to DI one. I’m guessing the answer here is to make it a constructor parameter.

        Thanks! I’m using StructureMap, by the way. If I end up producing anything worth sharing I’ll add a comment and link to a GitHub repo.

  • Pingback: Sending Emails in Asp.Net Identity using Dependency Injection, Sendgrid and debugging it with Mailtrap.io « Trailmax Tech()

  • Mike Harrison

    thank u for your fantastic post , i have one question , since i cant use depency injetion with attribute filters , if i want to force a loged in user to log out , how can i do this in this enviement ?

    • Logging users out are easy. Logging-in and logging-out are a function of IAuthenticationManager. And that is provided by OWIN from HttpContext.GetOwinContext().Authentication.

      So you attribute should will look like this: https://gist.github.com/trailmax/5f8756af131c874c9122

      However, this attribute seems a bit out of place to me. Logging out is either done by user himself – a specific action. Or as a result of some action that was performed by a user – part of the action and should be done specifically in the action, not as an attribute.

      And to do DI into controller/action attributes I used this trick: create an empty marker attribute that only inherits Attribute class. Apply this attribute on controllers/actions when you need. Create a global filter (where you can do constructor injections) and apply them globally in FilterConfig.cs. On every action execution check if controller/action has the marker attribute applied through reflection. If your attribute is present, execute your action. No marker -> nothing happens. But beware that instances of filters live across many requests and most of MVC dependencies (especially EF DbContext) should not live longer than a request and lifescope of objects can be mismatched, creating “captive dependency” problem. I can find you articles to read if you need to solve this problem – let me know.

  • kubicek

    thanks a lot for a very clear and detailed post trailmax! you just saved me next couple hours of googling… this serviceLocator pattern introduced by Owin by default has bugged me on the project I am working on for weeks now and finally I was able to clear the mess. awesome post

  • Raj

    Newbie question. So say I register my own class in unityconfig e.g container.RegisterType();

    If I now have a controller say TestController which has loads of actions but the ITest dependency is only required in one of them, I’m guessing it would be a bad idea to use constructor injection. If I want to resolve the dependency just as a one-off in a particular action, what would be the syntax? I tried GetConfiguredContainer but this doesnt give me the option to resolve the type as far as I can tell?

    Thanks

    • If your controller has that many actions, it is probably violating Single Responsibility Principle and should be split into smaller parts. I’d start with that – most elegant and future-proof solution.

      Other than that you can try doing action injections , i.e. your actions will look like this:

      `public ActionResult MyRareAction(ViewModel model, ITest myDependency)`

      but I don’t know how this can be done with Unity (could well be that this is not possible with Unity, I don’t know). This is a hack and not recommended. Every time I’ve done it in the past caused issues.

      Another not-recommended approach is to use service locator:

      public ActionResult MyRareAction(ViewModel model){
      ITest myDependency = DependencyResolver.Current.GetService();
      // other stuff
      }

      This is an anti-pattern that is discouraged to be used. Because reasons: http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/

      • Raj

        Agreed with Single Responsibility principle. But even if I only had 2 actions and but only 1 of them needed instances of lots of classes, wouldn’t it be a waste of resources passing them in the default constructor?

        (BTW, completely agree with the Service Locator pattern. One of our old apps used Ninject with this and it slowly became a pain..)

        • re “waste resources”: constructing your object graph should be cheap and easy and constructors should not do anything other than assign dependencies to local variables. So until you start using your dependencies they don’t use much of the resources.

  • Alexander

    Hello, thanks for your post! I have a question. How I can use Identity EntityFramework 2 and IoC Container if my application has the following architecture: Data Access Layer – Domain – Web application. DataContext located in Data Access Layer. Maybe do you have an example?

    • Alexander, unfortunately I don’t have an example. There are 2 approaches here: let ApplicationUser live in DAL layer, next to DbContext. This will make ApplicationUser object invisible in Domain, and do a weak link to business objects via username or user.id. Or Add Entity Framework to Domain layer and have ApplicaitonUser live in Domain layer. This way you’ll be able to specify foreign keys on DbContext level (which still lives in DAL).

      There is really no preference in that. I’ve got 2 quite big projects (one 200K lines of code, another 80K LoK) and in one I let Identity stuff live in DAL only, in another I let EF leak into domain project. Both work well and I have not encountered any problems yet.

  • Raj

    So Im starting a new project where I will be creating a Web API and no UI for now. What would be the best project structure for this? If I start a new WebApi project, it will be default add the Identity stuff into into, which going forward will be a pain (when I decide to create a UI). Any suggestions?

    • These days all my greenfield work is one giant project file with everything in it. And classes for testing in separate. I’ve bumped more bruises over project separation than gained any value. Remember, application layers != projects. Also it very much depends on your requirements. If MVC/WebApi is all you going to do, then one project can be good enough. But if you are exposing endpoints in WCF or doing offline WPF application that uses the same domain, than you should separate domain stuff out from UI. But this is your call, I can’t advise on that, other than answer the question “If you are going to separate your work into projects, what will you gain from that?”

      • Raj

        The question is arising due to the hosting. E.g I will want to have a separate end point for my API vs my web application. I thought the whole point of using MVC was to separate the domain at least, and Identity should really form part of this no?

        • Yes, you get your separation, even if all your classes are in one project. Again, projects are not layers and are not required for separation.

          If your WebApi is going to be deployed separately from MVC, then sure, have a domain project with Identity models and then have a project for MVC and another project for WebApi, both of the UI projects depending on the Domain, but Domain is ignorant of the UI tech. And configuration of Identity in MVC and WebApi will be different, so it’ll make sense.

          • Raj

            so I guess that is my question – how simple is it to move Identity to a domain? It seems like a bit of a nightmare considering all the config and owin stuff wrapped in a ‘default’ project.

          • If it is configured like I describe above, all you’ll have to do is to add Identity.EF nuget to your Domain, then move all related classes (5-6?) into domain and fix namespaces. I think it’ll take me 20-30 minutes, so nothing close to a nightmare -)

          • Raj

            Ok Im at that point, but what about the OWIN references in the classes? Should I add owin on the Domain layer? I would have thought I would need to keep that at the UI layer. Not trying to be lazy, but would it be possible for you to adapt your example project to show this kind of setup? (I think it would be quite valuable for many readers). Thanks

          • No, OWIN should live in UI layer. The only reference to OWIN in the classes I see is IDataProtectionProvider but that can be hooked-in via DI.

            OK, I got your hint -) In the next couple days I’ll write up another blog post on separation of Identity into a separate project.

            And possibly I’ll add CQRS approach. Would you be interested in that?

          • Raj

            Much appreciated! Ive never really come across CQRS to be honest. I would be looking to use a repository pattern for the crud operations if that helps?

            From the API and Web UI layers, I would be looking to do social login connects using the authtoken system so any assistance on that would be great too.

            Cheers!

          • CQRS is not complex, just different approach. Read this if interested: https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91 and https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92

            As for Social Logins, there are plenty of other blogs/documentation covering this, so I won’t go there.

          • Raj

            Hey, Im just trying to make some progress with this myself today. With the ApplicationSigninManager class, Im guessing that has to remain in the UI layer due to its reliance on OWIN. So really all I need to do is move the Models, ApplicationUser class?

          • Yep. ApplicationSignInManager is just a helper class for LoginController, so should stay in UI.

          • Raj

            I think Im almost there with this, but am having a bit of trouble with the WebAPI ApplicationOAuthProvider. In its default constructor it takes a publicClientId parameter but I also need to inject the ApplicationUserManager into this. Im sure this is possible but I am not sure how to go about this with Unity. Any advice?

          • Raj

            Have tried this in Unity config by the way.

            container.RegisterType(
            new InjectionConstructor(typeof(string), typeof(ApplicationUserManager)));

          • Raj

            Ok I have hit a brick wall. I have managed to get the WebApi account controller working with this

            container.RegisterType(new InjectionConstructor(typeof(ApplicationUserManager)));

            So this allows me to register and login. The bit I am still struggling on in the ApplicationOAuthProvider and how to inject the ApplicationUserManager in to in. I have tried adding a default constructor and injecting it in but it always returns null, so fails to generate a token.

            Any help appreciated!

          • Sorry, been very busy. Re ApplicationOAuthProvider – just seen your question on SO. I’ll answer there, it is a more suitable medium.

  • Gabriele Gaggi

    Thanks a lot! You save my life! :-)

  • Guest

    Do you know why for each request are created multiple instances of ApplicationUserManager? is Owin fault?

    • Very much depends on the set up. You’ll need to show registration code and OWIN code to figure out.

      • Guest

        I use exactly your code, the only difference is that I use SimpleInjector (like in your repo in GitHub). If you put a breakpoint on ApplicationUserManager constructor you see that is called two times every request. Are the instances used by controllers and owin for cookies different? Both should be served by the IoC container.

        • I have a suspicion that OWIN instance is called before the IoC have a chance to spin-up. However, OWIN only makes use of UserManager only in one place – cookie invalidation on security stamp update. And it should not make much difference if the instances are different.

          I’ll look into that once I have a minute.

          • Guest

            It’s my guess too. Thanks.

  • Bob

    Thank you. But as long as you are using and injecting concrete classes like ApplicationUserManager and ApplicationSignInManager, it’s not called inversion of the control. These classes should be accessed through their equivalent interfaces.

    • Um. Yes and no. I have tried wrapping an interface around these classes and made a mess of it. There are no alternatives to these classes, i.e. you are not going to be injecting different implementations for these classes, so what is the point?

      Unit testing? I have 4 production projects with these classes tested via integration tests where I go directly into DB. The only mocked object is IAuthenticationManager. Tests work fine, projects work fine.

      Complexity. Certainly adding interfaces will add extra complexity to projects. And people already struggle with these classes. Add another layer of pointless (prove me wrong) abstraction won’t help with understanding.

      Also, what methods are you going to put in the interfaces? UserManager is massive. Also how you going to deal with sync-run extension methods (Find() vs FindAsync())?

      • temporaryuser381

        Well, since we can’t easily add interfaces here, i’m using abstract classes. Abstract Classes inherit from identity classes and my concrete implementations inherit from abstract classes.

        • And what gain do you get from this indirection?

          • temporaryuser381

            All my Interfaces are in one Project named Core. I never use concrete classes anywhere. Plus My Concrete Classes can be as deep in heirarchy as i want. So, i can place these files in DAL where they belong. While DAL i below Infrastructure and Presentation Layer.

          • Sure, if that works for you.
            I used to be religious about this separation, but recently stopped doing separation of DAL/BLL into projects if BLL is not going to be used elsewhere. Makes life easier in a small projects.

          • temporaryuser381

            yeah i am actually working on very huge projects. So i need lots of separation to future upgradations. Beside this will allow me to easily mock UserManager and RoleManagers for unit testing. And only Core project will reference DAL project. Every other project can only have reference to Core project.

          • My main project is 230K lines of code. And many times I wish there was no separation of layers in different projects. As for tests, I prefer to do integration tests, when it comes to Identity framework – no good way to do a realistic mock of Identity framework.

  • Bob

    Instead of
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    It’s better to inject the `IDataProtectionProvider dataProtectionProvider` to ApplicationUserManager class and then at start up we can configure the IoC like this:

    private void configureAuth(IAppBuilder app)
    {
    SmObjectFactory.Container.Configure(config =>
    {
    config.For().Use(()=> app.GetDataProtectionProvider());
    });

    • Yes, that’s a good suggestion. I have thought of improving this bit, but did not pay enough attention.

      • Mike Dymond

        If you where to do this in Unity how would you configure the container, given that you do not currently have access to app in the RegisterTypes method?

        • I’ve just tried and got it working easily:

          See this line for registration: https://github.com/trailmax/IoCIdentitySample/blob/Part2/IoCIdentity/App_Start/Startup.Auth.cs#L20

          And then you just inject IDataProtectionProvider into ApplucationUserManager: https://github.com/trailmax/IoCIdentitySample/blob/Part2/IoCIdentity/Identity/ApplicationUserManager.cs#L12

          • Mike Dymond

            Really? I have just tried to do what you suggest and am getting compile errors. The line

            UnityConfig.GetConfiguredContainer().RegisterInstance(app.GetDataProtectionProvider());

            fails because RegisterInstance has 4 parameters but is only called with 1.

            Also, since we are not registering this instance against an interface how can the DI container inject the correct object into the constructor of ApplicationUserManager?

            Once again, thanks for answering my questions and I am sure I am just missing something obvious.

            Cheers Mike

          • With the build fail, make sure you have namespace `Microsoft.Practices.Unity` added to the file – this `RegisterInstance` is actually an extension method coming from `Microsoft.Practices.Unity.UnityContainerExtensions`

            As for lack of Interface, Unity can do this – it registers all the classes for their implemented interfaces, also it can resolve concrete classes without implicit registration. Something that can be very useful. Or very scary when you have a few implementations of the same interface.

          • Mike Dymond

            Right, of course, hate it when that happens. All that that extension method does is exactly what I did in my code, except that is used the ContainerControlledLifetimeManager (i.e. a singleton) whereas I used TransientLifetimeManager, which given that we are registering an instance is correct.

          • Mike Dymond

            OK, I had a play and got it working. This is my config code in Startup.Auth.

            var container = DependencyResolver.Current.GetService();
            container.RegisterInstance(typeof (IDataProtectionProvider), null, app.GetDataProtectionProvider(), new TransientLifetimeManager());

            I don’t like the fact that I now have DI configuration in two separate places, but I can’t see how that can be helped, unless I moved all the config here or somehow injected app into the existing config code.

            Also I changed how my code gets hold of the container. (I really hate static methods!)

            In case you didn’t know (I seems to remember you said the Unity was not you DI of choice), whenever you create a Unity container, the first thing it does is register itself with itself. In other words you can use the container to get an instance of the container. So seeing as I already have access to DependancyResolver I can use that to get the container and then add config.

            Thanks again for your help.

            Cheers Mike

          • Correct, I’ve never used unity before writing this article. But most of the containers can resolve themselves if you ask for `IContainer` or similar interface.

            Unfortunately with this set up of OWIN and DataProtectionProvider, whatever you do will be a fudge. As I’ve done originally – save a reference as a global static, then re-use it. You can train your container to access this global static (probably as a delegate, not directly in case DI is configured before OWIN) and inject instance into consumers. You can re-configure container (as you have done above). All these seem to be a little hacky. But as long as no pink fluffy bunnies die over your code, it is all good -) So I would not waste much time over perfecting this issue.

  • temporaryuser381

    first of all, thank you for this awesome post. It really helped me save lots of time.
    I just have one little problem, hopefully you can help me. I want to access my DBContext instance during onValidateIdentity Callback execution (during SecurityStampValidation). But since i am creating DbContext Per Request we can’t access it there. Because, this callback is executed in IIS pipeline even before HttpContext is created. Can you please guide me how would i solve this problem?

    • he, that’s a good one!
      I have opted into manual creation of DbContext just for that case. I mean I did not use DI container to create my object, but done old-school `new DbContext(“connectionString”)`. One of the reasons for that you stated yourself. In 2 of my projects I ended up with cyclic dependency (on IPrincipal) that I had to break somehow and not using a container was a good solution.

      In SecurityStampValidation event, DbContext is only used for reading ApplicationUsers table and comparing security stamp in cookie with the one in DB. No writing happens there. So there is no danger of having multiple DbContext instances – one early in the pipeline for Identity, another one from your DI container for you operations.

      Sometimes DI containers only frame you in a box. One needs to learn when to use it and when to break free – this is the case when you need to break free -)

      • temporaryuser381

        thnx.

  • Mike Dymond

    I have encountered a problem after implementing your code. My Db seeding method no longer works, it get to the first time it makes a call to the RoleManager and just hangs, giving no error message.

    public static void InitializeIdentityForEF(ApplicationDbContext db)
    {
    var userManager = HttpContext.Current.GetOwinContext().GetUserManager();
    var roleManager = HttpContext.Current.GetOwinContext().Get();

    const string name = “XXX”;

    const string password = “XXX”;
    const string roleName = “XXX”;

    //Create Role Admin if it does not exist
    var role = roleManager.FindByName(roleName);
    if (role == null)
    {
    role = new IdentityRole(roleName);
    var roleresult = roleManager.Create(role);
    }

    var user = userManager.FindByName(name);
    if (user == null)
    {
    user = new ApplicationUser { UserName = name, Email = name };
    var result = userManager.Create(user, password);
    result = userManager.SetLockoutEnabled(user.Id, false);
    }

    // Add user admin to Role Admin if not already added
    var rolesForUser = userManager.GetRoles(user.Id);
    if (!rolesForUser.Contains(role.Name))
    {
    var result = userManager.AddToRole(user.Id, role.Name);
    }
    }

    This code was from a Microsoft example and I don’t really like it, but I am still intrigued as to why it should stop working after I make your suggested changes.

    And yes I am loading the RoleManager into the OwinContext. I have also tried changing the seeding method to use DependencyResolver (after registering both managers in the container) but that gave exactly the same result.

    Is there something I have overlooked? Also any idea why any exception that might have occurred in the Asp.Net Identity code is not bubbling up to the UI?

    Any help much appreciated

    Cheers Mike

    P.S. did you ever produce an example of a proper n-tier application with Asp.Net Identity?

    • Hanged code with no exception sounds like async problem. All the Identity code is primary async/await and sync methods are actually extension methods. Though I have not seen any async methods in your examples, so it is strange. I certainly would not depend on OwinContext because it relies on HttpContext to be there, and there is a big chance that in DB-seed HttpContext is not available yet (though very much depends how it is wired).

      Another thing that I’ve noticed that you get `result` objects from user/role creation but do not inspect them for failed executions. I’d connect debugger and check where exactly the code hangs and if any objects are null.
      Also I see that you overwrite `result` object when you create user and then set lockout – try creating a separate variable for the second result. Because all this code is asynchronous, but wrapped in a sync extension methods, it can be funny and cause deadlocks.

      • Mike Dymond

        As I said none of this code is mine and I agree with the issues that you raise.

        When you say I should attach the debugger what do you mean? Is there something I have missed?

        I have set a breakpoint in that code and I can step through it fine until it reaches the

        var role = roleManager.FindByName(roleName);

        line. If I try to step over it, it hangs. If I try to step into it, it hangs. Is there a way of forcing the debugger to step into source code that is not part of your project? I can use Resharper to download the source code for RoleManager, but I can’t get the debugger to follow execution into that file.

        Any help is greatly appreciated.

        Thanks Mike

        P.S. As I said before I am going to be re-writing all the data access code and will implement the seeding routine in a very different way (I really don’t like that it actually has the password in plain text in the source!) However I am still keen to get to the bottom of this issue as I want to make sure that it is not highlighting a flaw in how I have implemented Identity that will come back to bit me later.

        • Attach debugger == run in debug mode and step through code execution with break-points.

          Handing on `roleManager.FindByName` is an indicator that there is a bug in extension method. Try replacing this by `await roleManager.FindByNameAsync` and add related `await` and `Task` instead of `void`. See if that works.

          As for the flaws in that seed routine – that looks OK to me from Identity point of view – pretty standard piece of code and I have very similar things for creating admin users in a few of my projects. Only I’m not calling that from EF Seed() method – stand-alone component executed in start-up routine with dependencies injected via DI-container

          • Mike Dymond

            The reason I asked about attaching the debugger is that I have had problems debugging seeding code before and had to use code to attach the debugger, I wondered if you meant that.

            As for there being a problem in the FindByName extension method, this is not an extension method in my code, it is part of Identity.Core

            public static TRole FindByName(this RoleManager manager, string roleName)
            where TKey : IEquatable
            where TRole : class, IRole
            {
            if (manager == null)
            {
            throw new ArgumentNullException(“manager”);
            }
            return AsyncHelper.RunSync(() => manager.FindByNameAsync(roleName));
            }

            I can now get the debugger to step into other framework code, but still cannot get it to step into this code. Just hangs.

            I am pretty new to Async programming so not really sure what you want me to try? I have tried calling

            var role = await roleManager.FindByNameAsync(rolename);

            But it says I can’t use the await term because the method is not marked with async, which of course it is?!?!?!

            Very confused.

            Cheers Mike

          • Try moving the initialisation code to controller and hook it up so it is executed from controller directly – just to see if async version works or not.

            Just like this: https://gist.github.com/trailmax/a69004170220b639880c (disclaimer – might not compile, have not tried it)

            Extension method: what you quoted – that is what I meant. Natively UserManager does not have sync methods, they are added via additional static class. There could be bugs in that class that provides extension methods (but it does look pretty bog-standard)

          • Mike Dymond

            I pretty much did as you suggest and as I have said in my other post I seem to have gotten to the bottom of it, but of course still do not know why it worked for a while and then stopped working. But I am now happy with what I have, especially given that I am about to completely re-write it :-)

            Thank again

            Cheers Mike

          • Mike Dymond

            OK, I have not exactly figured out what is going on, but I do now have it back to a point where it is working. Firstly I changed the return type of the seeding method to async Task. Then I made the first call using await RoleManager.FindByNameAsync(rolename). From then on I could just keep the existing code that call exactly the same function but not the async version and it is now all working fine.

            As I said async programming is still new to me so if you have any idea why this might be I would be very keen to know.

            Cheers Mike

          • No exact idea why this happens. My best guess is a deadlock due to a defect in Identity code.

    • As for the last question, do you mean to ask for separating `ApplicationUser` class to be in Domain Layer and `UserManager` in Data Layer. But do not take EF dependency in the Domain. Then no, I have not spent any time on that. I’ve seen how people have done that, but it took a lot of effort and a lot of extra code to maintain.
      I feel there is no benefit in this separation and I’d rather churn out extra features for business value than spend any time on separating “layers” that will bring no value to project owners, but increase the costs and maintenance efforts significantly.

      I have converted 2 large(ish) projects from MembershipProvider to Identity and in one I added EF to the Domain Layer and created `ApplicationUser` there, with all the rest of the stuff in DAL. And after adding EF to Domain Layer I expected thunder and lightning to break through and me to fall through my floor down to the Hell…. but it did not happen -)
      In the second project I kept all the Identity stuff in DAL/UI layers and did not bring `ApplicationUser` class to the Domain, just given GUID UserId to domain classes. And that also worked excellently. Both projects are heavily used in production at the moment and so far we have not experienced any issues with both of the setups.

      • Mike Dymond

        I agree that moving ApplicationUser and UserManager makes little sense. What I was proposing was to have all of my Entities (including the ones for Identity) in one project as POCOs. Then a Data layer that contains the DbContext, a generic Repository to access the data and the various Stores that Identity need (these will then by injected into the ApplicationUser using DI). Above that will be a Business layer with all of my my Services in and then finally the UI layer which will be the website.

        This seems very easily achievable from what I have read and it gives me the separation and testability that I want.

        What are your thoughts on this?

        • Identity models (ApplicationUser, ApplicationRole and related) are coming from Idetntity.EF package which in turn depends on EF. So if you don’t mind Identity and EF dependencies in your Domain project, then there will be no problem at all – that’s what I have in the first project I mention.

          Regarding testability, I highly recommend doing integration tests for Identity-related classes and don’t bother with mocks. You’ll never set up mocks to be similar to actual Identity classes, hence your tests will not be real ones.

          • Mike Dymond

            Thanks.

  • Anon

    Awesome!

  • Craig Cronin

    Luckily came across this post even though I was using structuremap, the concepts saved me after 5 hours of debugging :)

  • Виталий Литвинюк

    Hi, Max! Thx for your guide, it’s great! But I have a question. I use SimpleInjector and good practice is call container.Verify(); after dependency registrations, but on this method application crashes. What can I do with this?

    • Simple – don’t use that method. This method creates instances of all registered classes, but IAuthenticationManager takes dependency on HttpContext and it is not available at the time when you try to execute this Verify() method.

      Also usefulness of this method is very arguable: http://blog.ploeh.dk/2011/12/21/TestingContainerConfigurations/ DI-self testing is not very practical

    • TheBigRic

      I would advise againt not verifying the container. Verifying is actually a very practical tool to spot common mistakes. By making small adjustments in the registration of IAuthenticationManager verifying the container is no problem at all. I wrote a stackoverflow answer (http://stackoverflow.com/a/28948205/3294832) in which I explain why verifying is usefull and how you register IAuthenticationManager in order to let Verify() succeed.

  • Tim Baart

    This worked great for me, but after doing some testing I found out that the UserManager returned by the IOwinContext is always the same object. It gets created by the Unity Container the first time it is used, and will never be disposed. I did add this line to the MVC Activator:

    Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));

    Yet the UserManager is not resolved per request.

    The UserManager used as arguments in Controllers (which are part of the WebApi activator, instead of the Mvc Activator) do get resolved every request. I managed to set that up right.

    How do I get this to work? Or rather – is it even necessary to get this to work? Considering the UserManager used by Identity is only used to read, not to write, is there any harm in having it only be resolved once?

    Thanks for the article nonetheless. Saved me a lot of trouble!

    • Felipe Correa

      Facing the same problem but with my EntitiesContext. I have been unable to get an instance in a Per Request Basis :-/

      Did you get around this?

      • Is this causing troubles? see my comment above.

        • Felipe Correa

          Yeah, it is still causing problems and I figured what my problem is. I still saw the error because my controller actions are “async”.

          Do you know how to correctly configure the lifetime of an object inside unity when it is going to be injected after an “async” function is called?

          • sync or async, it should not matter to Unity. Have a look on this answer http://stackoverflow.com/a/22895257/809357 for scoping ideas. Unity is not my container of choice – I don’t know any better.

          • Felipe Correa

            It didn’t work with any of the options I have found including your suggestion… I don’t know what to do to make it work properly. There should be a new instance with every request but it seems to be broken somehow.

          • Ivan Limansky

            Is this still an issue with the latest Git codebase?

            Thanks!

    • Sorry, somehow I have missed your comment and noticed only now.

      I have seen other people reporting the same problem before, however I have not done anything with this to prove the statement.

      But I have traced the source code where UserManager resolved from IOwinContext and how it is used. I can confirm that UserManager in that case is only used to read data and never writes (see here https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Owin/SecurityStampValidator.cs)

      So there is no harm in having this UserManager to be a singleton. As long as you resolve UserManager for your controllers from the container and that is scoped per request.

  • Roger Swetnam

    Hi Max:

    Thanks so much for this. I am trying to take an app that I have which uses StructureMap and upgrade it to use the Identity framework.

    I am having problems figuring out how to translate the following statement into StructureMap :

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

    Wondering if you or someone looking at this might be able to give me ah hand.

    Thanks,
    Roger

  • Alan Wolman

    Thanks for this post – getting Unity and Identity framework working seamlessly without this info would have been very hairy.

  • Milad Ashrafi

    Super LIKE

  • Thanks for the great article.
    To help anyone using Ninject, here is the bindings I used.

    kernel.Bind().To(); //must not be in request scope -> owin db disposed error

    kernel.Bind().ToSelf().InRequestScope();

    kernel.Bind().ToMethod(c => HttpContext.Current.GetOwinContext().Authentication);

    kernel.Bind<IUserStore>().To<UserStore>().InRequestScope();

    • disqus_cRXF13od5I

      Hi Robert,

      I am trying to use this with nijnect, but when making the calls to get an Token using the Oauth GrantResourceOwnerCredentials with OWIN , when making FindByNameAsync call it fails with the error:

      Object name: 'ApplicationUserManager'.]
      Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName) +168
      Microsoft.AspNet.Identity.<>c__DisplayClass1`1.<RunSync>b__0() +53
      System.Threading.Tasks.Task`1.InnerInvoke() +79
      System.Threading.Tasks.Task.Execute() +110
      System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
      System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
      System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +49
      Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +412

      Could you please give an advice?

      • Sorry, I can’t tell from looking at your stack trace. If you still haven’t found it, try posting a question about it on stack overflow. Make sure you include the exception message not just the stack trace and include a link back to this article.

  • Mubeen

    This article helped me a lot to configure and use Unity with Owin based identity. Thank you very much! Much appreciated.

  • Bulut Paradise

    What about the ApplicationRoleManager?

    I’m using this class

    public class ApplicationRoleManager : RoleManager
    {
    public ApplicationRoleManager(IRoleStore roleStore)
    : base(roleStore) { }

    public static ApplicationRoleManager Create(
    IdentityFactoryOptions options,
    IOwinContext context)
    {
    var manager = new ApplicationRoleManager(
    new RoleStore(context.Get()));
    return manager;
    }
    }

    and im getting “Object not set to an instance of an object” error

  • Rodrigo S. Teixeira

    Thank you so much for sharing your resolution. I’ve been working all day trying to solve dependency injection. You save my day! :-D

    Instead of define the property “Startup.DataProtectionProvider”, I just set “IDataProtectionProvider dataProtectionProvider” as parameter on ApplicationUserManager class. And on injection, I’ve wrote only:

    app.CreatePerOwinContext(() =>
    DependencyContainer.Resolve(null, new ParameterOverride(“dataProtectionProvider”, app.GetDataProtectionProvider())));

    In case you still in need, you may use this approach.

    Thanks your your time, sharing this article!

    • That might be pretty neat. But does it inject `IDataProtectionProvider` into userManager when it is resolved outside of OWIN?

  • Ibrahim

    Why does contents of Create method need to be moved into the constructor? Without changing the managers I can get injection work ok it seems.

  • Wojciech Sura

    Thanks for the article! You cut me a lot of work.

  • Daniel Mackay

    Awesome article. Thanks mate!

  • Stefan

    Instead of hooking up the options in the startup class it’s possible to register for DI like this:
    container.RegisterType<IdentityFactoryOptions>(new PerRequestLifetimeManager(),
    new InjectionFactory(c => new IdentityFactoryOptions()
    {
    DataProtectionProvider = new DpapiDataProtectionProvider(“MyASPNetApplication”)
    }));

    • And does this work for you? I remember I tried something similar and could not get it to fly – I could not verify the tokens.

      • Stefan

        I haven’t tried using external providers as of yet, I’m only just touching this. But I am able to login, create a new user etc.

        In the ConfigureAuth function i’ve commented out all three app.Create… statemements, and my unity registrations look like this:

        container.RegisterType<IdentityFactoryOptions>(new PerRequestLifetimeManager(),
        new InjectionFactory(c => new IdentityFactoryOptions()
        {
        DataProtectionProvider = new DpapiDataProtectionProvider(“MyASPNetApplication”)
        }));
        container.RegisterType(new PerRequestLifetimeManager(),
        new InjectionFactory(f => HttpContext.Current.GetOwinContext().Authentication));

        container.RegisterType(new PerRequestLifetimeManager());
        container.RegisterType(new PerRequestLifetimeManager(),
        new InjectionMethod(“Configure”, new ResolvedParameter<IdentityFactoryOptions>())); // After construction

        EDIT: And in my service layer (which has access to the data access layer) I have this registration: container.RegisterType<IUserStore, UserStore>(
        new InjectionConstructor(typeof(MyDb)));

        • Check if your password reset works. You might find that `DpapiDataProtectionProvider` registered like that does not validate issued tokens. But I might be wrong – I currently have no means to check.

          • Stefan

            It works :)

          • Good stuff! When I have a chance, I’ll validate your findings and will update the post.

      • Stefan

        It worked. I had to set up smtp first to receive the reset link but once that was done, i received a link which allowed me to reset my password.

  • Andrew Kuzovov

    There is a part here which I don’t like. It’s about IAuthenticationManager:

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

    Is it possible to get rid of HttpContext?

  • Habbex

    Worked lovely for me too, but I came here because of I missed the whole thing that also identity need DI. Anyway my problem is trying to retrive a list of users with roles.. but with this new knowledge I may be one step closer solving it. So it anyone want to help please feel free to do so :)

  • Craig

    Hi, great post, really helped shed some light. I implemented this into my own project and up until recently thought everything was running ok until I updated my Micrsoft.Owin to 3.1 and suddenly I started received errors in my log files.

    System.InvalidOperationException: No owin.Environment item was found in the context

    I believe this is happening because HttpContext.Current is null in my UnityConfig.cs file, specifically here:

    container.RegisterType(new InjectionFactory(o => HttpContext.Current.Request.GetOwinContext().Authentication));

    I ran your code from github and found the same issue. Any ideas how to solve this?