使用SimpleInjector为AccountController / ApplicationUserManager注册UserStore

时间:2016-09-01 19:49:44

标签: c# asp.net-web-api dependency-injection asp.net-identity simple-injector

我有以下通用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;
        }
    }

以下在IdetityConfig.cs中: -

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

我正在使用以下SimpleInjector来完成我的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>>();
    }
}

但是我收到以下错误: - “为了使容器能够创建UserStore<ApplicationUser>,它应该只有一个公共构造函数:它有2.请参阅https://simpleinjector.org/one-constructor以获取更多信息。”

任何人都可以帮助我并告诉我为什么我收到UserStore的以下错误?还有其他方法可以定义吗?

感谢您的帮助和时间!

1 个答案:

答案 0 :(得分:2)

只需将您的注册更改为以下内容:

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