How do I expose `UserManager` to

2019-02-28 16:31发布

I don't want to reference EntityFramework and hence Identity.EntityFramework with its IdentityUser in my domain. But I'd like to use UserManager of Identity.Core which uses IUserStore<TUser> where TUser : IUser<string>. And hence I need to expose that IUserStore while hiding ApplicationUser as it derives from IdentityUser.

In my data access layer:

public class ApplicationUser : IdentityUser, IApplicationUser { }

// somewhere for IoC container:
var userStore = new UserStore<ApplicationUser>();
// The following breaks with error CS0266: 
//     Cannot implicitly convert type 'UserStore<ApplicationUser>' to 'IUserStore<IApplicationUser>'
IUserStore<IApplicationUser> userStore = userStore;  // does not work
var um = new UserManager<IApplicationUser>(userStore);

In my domain layer:

public interface IApplicationUser : IUser<string> {}

// desired behavior somewhere in domain/web:
var myUserManager = iocContainer.Resolve<UserManager<IApplicationUser>();

This code does not work as TUser in IUserStore<TUser> is not variant (covariance).

1条回答
放我归山
2楼-- · 2019-02-28 17:11

It required me to write an adapter to Microsoft.AspNet.Identity.Framework.UserStore that inherits from IUserStore and thus can be used with UserManager. It maps my custom user object to IdentityUser. The gist for it can be found at https://gist.github.com/w1ld/b9228f5a27c54b061f90#file-userstoreadapter-cs Hope it helps someone!

查看更多
登录 后发表回答