如何在MVC应用程序中使用带有泛型存储库和UOW模式的ASP标识 [英] How to use ASP Identity with Generic Repository and UoW Patterns in MVC Application

查看:17
本文介绍了如何在MVC应用程序中使用带有泛型存储库和UOW模式的ASP标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的MVC应用程序中使用了通用存储库和UOW模式。它能很好地满足我的要求。然而,我发现很难将ASP标识与这些模式集成在一起,因为ASP标识与MVC紧密耦合。我的代码如下:

// Repository Interface
public interface IRepository<TEntity> where TEntity : class
{
        TEntity Get(int id);
        IEnumerable<TEntity> GetAll();
        IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
        void Add(TEntity entity);        
        void Remove(TEntity entity);
}

// Repository class
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
        // db context defined
        // IRepository implementation
}

// Domain Class
public class Author
{
        public int AuthorId { get; set; }
        public string Name { get; set; }
}

// DbContext class
public class AppContext : DbContext
{
        public AppContext() : base("name=MyContext") {}
        public virtual DbSet<Author> Authors { get; set; }
}

// Domain Interface
public interface IAuthorRepository : IRepository<Author> 
{  // implement custom methods }

// Concrete class implementation
public class AuthorRepository : Repository<Author>, IAuthorRepository
{
        public AuthorRepository(AppContext context) : base(context)
        {}

        public AppContext AppContext
        {
            get { return Context as AppContext; }
        }
}

// UnitOfWork interface
public interface IUnitOfWork : IDisposable
{
        IAuthorRepository Authors { get; }
        int Complete();
}

// Unit of work class
public class UnitOfWork : IUnitOfWork
{
    private AppContext context;

        public UnitOfWork(AppContext context)
        {
            this.context = context;
            Authors = new AuthorRepository(context);
        }

        public IAuthorRepository Authors { get; set; }

        public int Complete()
        {
            return context.SaveChanges();
        }

        // dispose context
}

public class HomeController : Controller
{
        private readonly IUnitOfWork uow;

        public HomeController(IUnitOfWork uow) // using Dependency Injection
        {
            this.uow = uow;
        }

        public ActionResult Index()
        {
            var authors = uow.Authors.GetAll();
            return View(authors);
        }
}

有人能为我提供有关如何将ASP标识与上述结构集成在一起的建议吗?

提前谢谢。

推荐答案

简明答案-您不能这样做。

长长的答案:默认模板为您提供了一个有效的解决方案,其中所有部分都很好地协同工作。为什么要费心将有效的解决方案捆绑到您的体系结构中,尤其是您意识到您的体系结构不适合通过身份解决的问题。

存储库和UOW模式很好,但不能用于标识。身份涉及身份验证、Cookie、角色和权限。存储库是持久化数据,UOW是事务。这些东西彼此不合身。所以,不要试图把一个圆钉塞进一个方孔里。

这篇关于如何在MVC应用程序中使用带有泛型存储库和UOW模式的ASP标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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