从服务创建用户管理器

时间:2018-03-28 17:35:11

标签: c# asp.net-mvc

我的UserService看起来像这样:

public class UserService : IUserStore<UserModel>, IUserLoginStore<UserModel>, IUserPasswordStore<UserModel>, IUserSecurityStampStore<UserModel>, IUserService
{
    private readonly IUserRepository _userRepository;

    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    //create the user
}

我想从此服务创建用户管理器。我创建了一个我称之为IdentityStartup的类,我看起来像这样:

public class IdentityStartup
{
    public static Func<UserManager<UserModel>> UserManagerFactory { get; private set; }
    private readonly IUserService _userService;
    //public static Func<RoleManager<Role>> RoleManagerFactory { get; private set; }

    public IdentityStartup(IUserService userService)
    {
        _userService = userService;
    }


    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/home/index")
        });

        // configure the user manager
        UserManagerFactory = () =>
        {
            var usermanager = new UserManager<UserModel>(_userService);

            // allow alphanumeric characters in username
            usermanager.UserValidator = new UserValidator<UserModel>(new UserService())
            {
                AllowOnlyAlphanumericUserNames = false
            };
            return usermanager;
        };

    }
}

正如您所看到的,我尝试将_userService作为参数传递,但这不起作用,因为它无法将IUserService转换为Microsoft.AspNet.Identity.IUserStore

我想将UserService用作UserStore。

2 个答案:

答案 0 :(得分:0)

只需让界面IUserService实现界面IUserStore<UserModel>

即可

这样的事情:

public class UserService : IUserService
{
    private readonly IUserRepository _userRepository;

    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    //create the user
}

public interface IUserService : IUserStore<UserModel>, IUserLoginStore<UserModel>, IUserPasswordStore<UserModel>, IUserSecurityStampStore<UserModel>
{
   ...
}

如果需要,您还可以将IUserService设为通用。

答案 1 :(得分:-1)

IUserService添加一个返回IUserStore<UserModel>

的方法
IUserStore<UserModel> asUserStore()

在您的实施中,由于IdentityService实施IUserStore<UserModel>,它可以自行返回

public IUserStore<UserModel> asUserStore() = {
  return this;
}