- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我们正在启动一个新的 Web 项目,该项目使用 C#/MVC 4 和 Entity Framework 5 进行数据访问。我已决定采用 n 层方法来构建项目结构,并且我希望获得有关我的设计决策的一些反馈。
解决方案的结构如下:
Project.Model(类库):包含 EF .edmx、实体模型和 View 模型
Project.DAL(类库):包含 EF DbContext 和 Repository 类
Project.BLL(类库):包含业务逻辑类
项目(MVC项目)
DAL
数据访问层只关心简单的 CRUD 之类的操作。我决定采用存储库方法。以下是存储库接口(interface):
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。因此,为了为每个请求创建和处理单个上下文,我编写了一个将 DbContext 注入(inject)到 HttpContext 中的 HttpModule。
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);
}
}
接下来是 Repository 基类。请注意,构造函数利用了上面 HttpModule 中注入(inject)的 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项目)
现在终于可以看到一个简单的 Controller 操作了:
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 上下文已妥善处理,整体速度良好。
这是解决这个问题的好方法吗?
感谢您的宝贵时间。
最佳答案
我认为如果你打算使用存储库模式,你应该将你的存储库视为 aggregates 对我来说,做一个存储库可以有一定程度的抽象,这很好但这样做可能导致存储库成为实体以中心为中心,有时这使得与属于同一聚合根的其他对象通信变得困难。
我前段时间遇到过这样的困境,我最终没有使用存储库 (T),而是使用了“通用存储库”中的方法 (T),这让我更容易对属于聚合的其他对象进行操作root (我这样做是因为它适合我,但这并不意味着它适合你,我把这个例子放在 table 上只是为了让你考虑它),你可以看看 this quesion和我发现非常有趣的 this article。
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>(); }
这与您在 repo 中所做的非常相似。
可能,我认为还需要 2 层(取决于您的要求),一层用于 services 以处理应用程序中的常见操作或操作,另一层可能用于组件(电子邮件、日志、缓存管理器、密码学、助手)等)
关于您如何处理 BL 的逻辑,在我看来有点矫枉过正,实际上您是在将存储库耦合到逻辑中,我个人认为这不太好。
尝试在您的应用程序中实现 Dependency Injection,因为您将从中获得很多好处。
假设您要创建一个 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){
}
}
然后您可以在您的 Controller 中实现该服务(如果您使用的是容器并仅调用登录服务,则将其注入(inject)构造函数)这将使您的实现更加清晰
public ActionResult Index(){
//then you're going to be able to use _userService.login()
}
这样你就会有一个 loosely coupled application ,理论上会更容易维护。
只是我的两分钱
关于c# - MVC 分层项目结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658212/
在 Django 中如何处理分层 URL?有什么最佳做法吗?例如。如果我有一个像 /blog/category1/category2/myblogentry 这样的 URL(使用例如 django-m
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,
有没有办法在 R 中创建这样的图表? 以下是图表中显示的数据的摘录: df % group_by(Animal) %>% unite(col=Type, Animal:Name, sep =
我一直在努力处理一些时间戳数据(直到现在才需要处理日期,并且它表明)。希望您能帮忙。 我正在处理来自网站的数据,该数据显示每个客户 (ID) 各自的访问以及这些访问的时间戳。它的分组是指一个客户可能有
我一直在努力处理一些时间戳数据(直到现在才需要处理日期,并且它表明)。希望您能帮忙。 我正在处理来自网站的数据,该数据显示每个客户 (ID) 各自的访问以及这些访问的时间戳。它的分组是指一个客户可能有
我正在尝试完成这段代码: ORDER BY IF(j.groups IS NULL OR j.groups = '', IF(j.title IS NULL, i.title), j.groups)
我有一个非常抽象的问题,因为我不确定如何提出它。我的其中一个 View 上有一个 UIImageView。我想让 ImageView 看起来“压入 super View ”。我不确定技术术语是什么,但
我希望 100% 宽的包含图像的 div 位于我的页面下方。在这些 div 之上,我想要一个 1210 像素宽的 div,我可以在其中放置我的内容。 例子: http://mudchallenger.
我目前正在做一个类似于 http://www.beoplay.com/Products/BeoplayA9#under-the-hood 的元素使用 Javascript、HTML5 和 CSS3。我
我想像上面那样创建图像缩略图..为此,我在下面创建了 XML activity_main.xml
我想知道是否可以定义一个分层 MapReduce 作业?。换句话说,我想要一个 map-reduce 作业,在 mapper 阶段将调用不同的 MapReduce 作业。可能吗?您对如何操作有什么建议
程序设计: A 类,实现较低级别的数据处理 类 B-E,为 A 提供更高级别的接口(interface)以执行各种功能 F 类,它是根据用户输入与 B-E 交互的 UI 对象 在任何给定时间只能有一个
CTE 对我来说有点新,所以我希望有人可以帮助我编写的以下内容将采用类别表并从中构建层次结构以进行显示。我知道这种事情一直被问到,但我认为我的排序情况使它有点独特。 我希望有一些使用 Hierarch
我有关于 的问题群 在聚类分析(层次聚类)中。例如,这是 的完全链式的树状图。虹膜数据集 . 我使用后 > table(cutree(hc, 3), iris$Species) 这是输出 : se
数据 我有以下(简化的)数据集,我们称之为 df从现在开始: species rank value 1
Delphi 2009 中的分层窗口和系统菜单存在问题。也就是说,我们的分层窗口(没有边框)没有系统菜单。当我说系统菜单时,我指的是单击应用程序的图标、右键单击其标题栏或(在 Windows 7 中,
我正在制作一个 pototype HMTL5 Canvas 动画,该动画将导出到 Quicktime。 我有一个动态生成的背景,上面有动态屏蔽的元素。 我可以获取要制作的背景,并将其作为逐帧动画(pn
好吧,我有一个打印棋盘的类和另一个打印国际象棋的类 如何使用 LayeredPane 将它们合并在一起,如上面的示例图片所示?我一整天都在尝试,但似乎没有任何效果。我正在使用 JFrame 打印图片。
这是我的场景。我有两个类(class) ClassA 和 ClassB。 B类继承A类。 我在它们两个上使用@Component注释来使它们成为Spring bean。 @Component publ
这不是一道问题题,而是一道使用工具——leiningen——的题。 在一个主项目下创建分层的 lein 项目是否有优势,如果有,优势是什么? 如果我使用 lein new bene-cmp 创建一个项
我是一名优秀的程序员,十分优秀!