How do I expose `UserManager<IApplicationUser>` to my business layer while hiding `IdentityUser`?

不想你离开。 提交于 2019-12-31 04:27:11

问题


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:


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!



来源:https://stackoverflow.com/questions/31024859/how-do-i-expose-usermanageriapplicationuser-to-my-business-layer-while-hidin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!