Search code examples
c#asp.net-web-apidependency-injectionasp.net-identitysimple-injector

Registering UserStore with SimpleInjector for AccountController / ApplicationUserManager


I have the following generic webApi2 AccountController:-

    private const string LocalLoginProvider = "Local";
    private ApplicationUserManager _userManager;

    public AccountController(ApplicationUserManager userManager,
        ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
    {
        UserManager = userManager;
        AccessTokenFormat = accessTokenFormat;
    }

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

And the following in the IdetityConfig.cs :-

    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

and I am using the following SimpleInjector to do my DI :-

public static class SimpleInjectorWebApiInitializer
{
    /// <summary>Initialize the container and register it as Web API Dependency Resolver.</summary>
    public static void Initialize()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

        InitializeContainer(container);

        container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

        container.Verify();

        GlobalConfiguration.Configuration.DependencyResolver =
            new SimpleInjectorWebApiDependencyResolver(container);

    }

    private static void InitializeContainer(Container container)
    {
        // For instance:
        container.Register<IFileHelpers, FileHelpers>();

        //container.Register<UserManager<ApplicationUser, string>>(
        //    () => new UserManager<ApplicationUser, string>(new UserStore<ApplicationUser>()),
        //    Lifestyle.Scoped);
        //container.Register<IUserStore<ApplicationUser, string>>(() => (new UserStore<ApplicationUser>()),
        //    Lifestyle.Scoped);

        container.Register<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
    }
}

However I am getting the following error :- "For the container to be able to create UserStore<ApplicationUser> it should have only one public constructor: it has 2. See https://simpleinjector.org/one-constructor for more information."

Can anyone help me and tell me why I am getting the following error for the UserStore? Is there any other way I have to define that?

Thanks for your help and time!


Solution

  • Just change your registration to the following:

    container.Register<IUserStore<ApplicationUser>>(
        () => new UserStore<ApplicationUser>());