2

我们正在使用 C#/MVC 4 和 Entity Framework 5 开始一个新的 Web 项目来进行数据访问。我决定对项目的结构采用 n 层方法,我希望得到一些关于我的设计决策的反馈。

这是解决方案的结构:

Project.Model(类库):包含 EF .edmx、实体模型和视图模型

Project.DAL(类库):包含 EF DbContext 和 Repository 类

Project.BLL(类库):包含业务逻辑类

项目(MVC 项目)

达尔

数据访问层只关心简单的类似 CRUD 的操作。我决定采用存储库方法。以下是存储库接口:

public interface IRepository
{
}

public interface IRepository<T> : IRepository, IDisposable 
    where T : class, new()
{
    T Add(T item);

    T Get(object id);

    T Get(Expression<Func<T, bool>> predicate);

    IQueryable<T> GetAll();

    IQueryable<T> GetAll(Expression<Func<T, bool>> predicate);

    void Update(T item);

    void Delete(T item);
}

在对在 Web 项目中使用 Entity Framework 进行了一些研究之后,普遍的共识是每个请求应该只有一个 DbContext/ObjectContext。因此,为了为每个请求创建和处理单个上下文,我编写了一个 HttpModule,它将 DbContext 注入到 HttpContext 中。

public class DbContextModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
        context.EndRequest += context_EndRequest; 
    }

    public void Dispose()
    {
    }

    private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext httpContext = application.Context;

        httpContext.Items.Add(Repository.ContextKey, new ProjectEntities());
    }

    private void context_EndRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext httpContext = application.Context;

        var entities = (ProjectEntities)httpContext.Items[Repository.ContextKey];

        entities.Dispose();
        entities = null;

        application.Context.Items.Remove(Repository.ContextKey);
    }
}

接下来是存储库基类。请注意,构造函数利用了上面 HttpModule 中注入的 DbContext

public abstract class Repository<T> : IRepository<T> where T : class, new()
{
    protected Repository()
    {
        if (HttpContext.Current == null)
        {
            throw new Exception("Cannot create repository - current HttpContext is null.");
        }

        _entities = (ProjectEntities)HttpContext.Current.Items[Repository.ContextKey];

        if (_entities == null)
        {
            throw new Exception("Cannot create repository - no DBContext in the current HttpContext.");
        }
    }

    private ProjectEntities _entities;

    public T Add(T item)
    {
        _entities.Set<T>().Add(item);
        _entities.SaveChanges();

        return item;
    }

    public T Get(object id)
    {
        return _entities.Set<T>().Find(id);
    }

    public T Get(Expression<Func<T, bool>> predicate)
    {
        return _entities.Set<T>().AsQueryable().FirstOrDefault(predicate);
    }

    public IQueryable<T> GetAll()
    {
        return _entities.Set<T>().AsQueryable();
    }

    public IQueryable<T> GetAll(Expression<Func<T, bool>> predicate)
    {
        return _entities.Set<T>().AsQueryable().Where(predicate);
    }

    public void Update(T item)
    {
        _entities.Entry(item).State = EntityState.Modified;
        _entities.SaveChanges();
    }

    public void Delete(T item)
    {
        _entities.Set<T>().Remove(item);
        _entities.SaveChanges();
    }
}

还有一个简单的实现示例......

public class AdminRepository : Repository<Admin>
{
    public Admin GetByEmail(string email)
    {
        return Get(x => x.Email == email);
    }
}

BLL

业务逻辑层封装了所有业务逻辑。为了保持约束,我编写了这样的基本“逻辑”类:

public abstract class Logic<TRepository> where TRepository : class, IRepository, new()
{
    private static Expression<Func<TRepository>> _x = () => new TRepository();
    private static Func<TRepository> _compiled = _x.Compile(); 

    protected Logic()
    {
        Repository = _compiled();
    }

    protected internal TRepository Repository { get; private set; }
}

构造函数自动创建所需的 Repository 类,因此在子类中不需要额外的代码来实例化存储库。这是一个简单的实现示例

public class AdminLogic : Logic<AdminRepository>
{
    public Admin Add(Admin admin)
    {
        return Repository.Add(admin);
    }

    public Admin Get(object id)
    {
        return Repository.Get(id);
    }

    public Admin GetByEmail(string email)
    {
        return Repository.GetByEmail(email);
    }

    public IQueryable<Admin> GetAll()
    {
        return Repository.GetAll();
    }

    public void Update(Admin admin)
    {
        Repository.Update(admin);
    }
}

这个例子更多的是对 DAL 存储库的传递,但以后添加业务逻辑不会有问题。我选择从 BLL 返回 IQueryable,因为我们正在使用一些需要 IQueryable 才能延迟执行的第三方工具。

项目(MVC 项目)

现在最后是一个简单的控制器动作的样子:

public ActionResult Index(int? page)
{
    // Instantiate logic object
    AdminLogic logic = new AdminLogic();

    // Call GetAll() and use AutoMapper to project the results to the viewmodel
    IQueryable<AdminModel> admins = logic.GetAll().Project().To<AdminModel>();

    // Paging (using PagedList https://github.com/TroyGoode/PagedList)
    IPagedList<AdminModel> paged = admins.ToPagedList(page ?? 1, 25);

    return View(paged);
}

一切都按预期工作,测试表明 EF 上下文处理得当,整体速度不错。

这是解决这个问题的好方法吗?

感谢您的时间。

4

1 回答 1

2

我认为,如果您要使用存储库模式,您应该将存储库视为聚合,对我而言,存储库可能具有某种程度的抽象,这很好,但这样做可能会导致存储库以实体为中心,有时这会变得困难与属于同一聚合根的其他对象进行通信。

前段时间我遇到了这种困境,而不是使用存储库(T),我最终在“通用存储库”中使用了方法(T),这使我更容易操作属于聚合根的其他对象(我这样做是因为这对我有好处,但这并不意味着对你有好处,我把这个例子放在桌子上只是为了让你考虑到它),你可以看看这个问题这个我发现非常有趣的文章。

Jeremy miller 谈到了如何实现IRepository

public interface IRepository { // Find an entity by its primary key // We assume and enforce that every Entity // is identified by an "Id" property of // type long T Find<T>(long id) where T : Entity; // Query for a specific type of Entity // with Linq expressions. More on this later 
IQueryable<T> Query<T>(); 
IQueryable<T> Query<T>(Expression<Func<T, bool>> where); // Basic operations on an Entity 
void Delete(object target); 
void Save(object target); 
void Insert(object target); 
T[] GetAll<T>(); }

这与您在回购中所做的非常相似。

潜在地,我认为还需要 2 层(取决于您的要求),一个用于服务以处理整个应用程序中的常见操作或操作,另一层用于组件(电子邮件、日志、缓存管理器、密码学、帮助程序等)

关于您如何处理 BL 的逻辑对我来说看起来和矫枉过正,实际上您将存储库耦合到我个人认为不好的逻辑中。

尝试在您的应用程序中实现依赖注入,因为您会从中获得很多好处。

假设您要创建一个 UserService,它具有您的 BL 的登录方法

public class UserService:IService {
    public UserService(IUserRepository, IMailer, ILogger){
      // for example you can follow the next use case in your BL
      // try to login, if failed reteat after 3 time you block the accunt and send a mail

    }

   public bool login(string username, string password){
   }

}

然后您可以在您的控制器中实现该服务(如果您使用的是容器并仅调用登录服务,则将其注入构造函数中)这将使您的实现更加清晰

public ActionResult Index(){
  //then you're going to be able to use  _userService.login()
}

这样,您将拥有一个松散耦合的应用程序,理论上它更易于维护。

只是我的两分钱

于 2013-09-25T20:21:56.263 回答