找到你要的答案

Q:How do I expose `UserManager` to my business layer while hiding `IdentityUser`?

Q:我如何让我` UserManager `业务层而躲` IdentityUser `?

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).

我不想参考identity.entityframework EntityFramework因此在我的领域的identityuser。但我想使用UserManager身份。核心采用iuserstore <;用户>;TUser:iUser <;字符串& gt;。因此我需要暴露,iuserstore躲applicationuser为来自IdentityUser。

在我的数据访问层:

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);

在我的域层:

public interface IApplicationUser : IUser<string> {}

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

这个代码不工作,在iuserstore & lt TUser;用户>;不变异(方差)。

answer1: 回答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!

它要求我写一个适配器microsoft.aspnet.identity.framework.userstore继承自iuserstore从而可以使用UserManager。它将我的自定义用户对象IdentityUser。它可以发现在HTTPS的要点:/ /依据。GitHub。COM / w1ld / b9228f5a27c54b061f90 #文件userstoreadapter CS希望它帮助别人!

asp.net-identity