如何转换UserStore< IdentityUser>到其基础类IUserStore< IUser&gt ;? [英] How to cast UserStore<IdentityUser> to its base class IUserStore<IUser>?

查看:79
本文介绍了如何转换UserStore< IdentityUser>到其基础类IUserStore< IUser&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将新的asp.net身份提供程序与我的模型域的抽象层一起使用,但该示例提供了Entity Framework的实现,因此我想在我的实体框架中使用现成版本的Identity与实体框架数据访问层.

I am trying to use the new asp.net identity provider with my abstraction layer of my models domain, wich have a implementation of Entity Framework, so I would like to use the out of box version of identity with entity framework in my data access layer.

如何转换

UserStore<IdentityUser> 

到其基本界面

IUserStore<IUser>

一旦UserStore是IUserStore的实现,我就可以通过以下方式进行转换:

Once UserStore is an implementation of IUserStore, I can get the cast by this:

UserStore<IdentityUser> as IUserStore<IdentityUser>

但是我想避免IdentityFramework引用和依赖项中的IdentityUser,以使我的域层保持松散耦合.因此,IdentityUser也是IUser的实现,可以将其强制转换为

But I want to avoid the IdentityUser from EntityFramework references and dependences, to keep my domain layer loosely coupled. So, IdentityUser also are an implementation of IUser I can cast it:

IdentityUser as IUser

这两种情况都可行,那么我想做一些这样的事情(实际上并不直接行之有效):

Both cases works, then I would like to do some like this (wich in fact doesnt works directly):

UserStore<IdentityUser> as IUserStore<IUser>

那么,我该如何实现呢?

So, how can I achieve this?

如果我们查看此关系图

If we look at this diagram http://i3.asp.net/media/4459023/1.png, we will see what I would like to achieve. Referencing just the Microsoft.AspNet.Identity.Core in my domain layer, but using Microsoft.AspNet.Identity.EntityFramework implementation at DataAccess layer by returning the core interfaces for the domain layer.

推荐答案

强制转换不起作用,因为 UserStore< UserIdentity> UserStore< IUser> 不同>(即使 IdentityUser 实现了 IUser ).

The cast doesn't work because UserStore<UserIdentity> is not the same as UserStore<IUser> (even if IdentityUser implements IUser).

如果您需要 UserStore< IUser> ,那么我建议您以这种方式实现它并在内部强制转换为具体类型,则可以确保具体类型为 IdentityUser 带有约束,例如

If you need UserStore<IUser> then I suggest you implement it in that way and cast to the concrete type internally, you can ensure that the concrete type is IdentityUser with a constraint e.g.

public class UserStore<T> : IUserStore<T> where T: IUser
{
}

您还需要使接口协变,即.

You would also need to make your interface covariant i.e.

public interface IUserStore<out T> where T : IUser
{
}

这应该允许您执行以下操作(假设 IdentityUser 支持 IUser )

This should allow you to do the following (assuming IdentityUser supports IUser)

IUserStore<IUser> userStore = new UserStore<IdentityUser>();

这篇关于如何转换UserStore&lt; IdentityUser&gt;到其基础类IUserStore&lt; IUser&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆