【问题标题】:How do I expose `UserManager<IApplicationUser>` to my business layer while hiding `IdentityUser`?如何在隐藏 `IdentityUser` 的同时将 `UserManager<IApplicationUser>` 暴露给我的业务层?
【发布时间】:2015-06-24 11:04:16
【问题描述】:

我不想在我的域中引用 EntityFramework 和 Identity.EntityFramework 及其 IdentityUser。但我想使用Identity.Core 中的UserManager,它使用IUserStore&lt;TUser&gt;,其中TUser : IUser&lt;string&gt;。因此,我需要在隐藏ApplicationUser 的同时公开IUserStore,因为它源自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&gt; 中的 TUser 不是变体(协方差)。

【问题讨论】:

  • 理想情况下,您也不会公开 UserManager,因为它来自 AspNet 命名空间。

标签: asp.net-identity


【解决方案1】:

它要求我为Microsoft.AspNet.Identity.Framework.UserStore 编写一个继承自IUserStore 的适配器,因此可以与UserManager 一起使用。它将我的自定义用户对象映射到 IdentityUser。它的要点可以在https://gist.github.com/w1ld/b9228f5a27c54b061f90#file-userstoreadapter-cs找到它希望它可以帮助别人!

【讨论】:

  • 您似乎实现了自己的 ApplicationUserStore - 您将其称为 UserStoreAdapter。我仍在尝试像 Asp.Net Webapplikation 模板那样使用 ApplicationUser 实现 UserManager,但我自己没有实现所有内容......但我还没有:(
  • 实现一个新的UserManager 应该会很顺利。不确定我是否理解其中的困难。我遇到的问题是我不想在我的项目中使用UserManager 引用Identity.EntityFramework
  • 我正在尝试一些非常相似的东西。我想将 IdentityUser (ApplicationUser) 分离到不同的项目 (Entities) 中。另一个项目应该包含存储库和另一个 WebApi 项目。这应该会在以后使测试更容易。如果您有几分钟的时间,我会在这里尝试一下:github.com/ddNils/TestWebApi02
  • @Nils 需要什么? 1)关键是您的测试是否应该在数据库上运行。表示您是否可以选择EF。我没有采取这种方式并没有EF。所以我使用适配器抽象出UserStore。您的代码现在依赖于 EF:IdenityUser。 2)UserManager 更像是一个业务逻辑,可以独立于UserStore,因此独立于 EF。你的版本在Repo,这很奇怪。 3) 因此,如果没有 EF 方式,则使 UserManagerApplicationUserIUser 继承它并删除所有 EF 引用。如果使用 EF,那么我看不出为什么不使用 UserStore
  • 对我来说,当从 Identity 继承时,我确实获得了所有属性(如用户名或电子邮件)。但是从 IUser 继承时,我必须自己编写所有属性。我的目标是不再发明轮子:当我只想再添加一个时,为什么要对所有用户属性进行编码?
猜你喜欢
  • 2012-08-01
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
相关资源
最近更新 更多