How to cast UserStore<IdentityUser> to its base class IUserStore<IUser>?

寵の児 提交于 2021-02-11 07:10:37

问题


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.

How can I convert an

UserStore<IdentityUser> 

to its base interface

IUserStore<IUser>

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

UserStore<IdentityUser> as IUserStore<IdentityUser>

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.


回答1:


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

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
{
}

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

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


来源:https://stackoverflow.com/questions/19929050/how-to-cast-userstoreidentityuser-to-its-base-class-iuserstoreiuser

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