如何正确设计数据访问层?
我有以下数据访问层(DAL)。我想知道它是否设置正确,或者是否需要改进?
public class User
{
}
//Persistence methods
static class UserDataAccess
{
UsersDAL udal = // Choose SQL or FileSystem DAL impl.
InsertUser(User u)
{
// Custom logic , is 'u' valid etc.
udal.Insert(u);
}
}
abstract class UsersDAL
{
GetUserByID();
InsertUser(u);
...
}
// implementaitons of DAL
static class UsersSQLStore : UsersDAL
{
}
static class UsersFileSystemStore : UsersDAL
{
}
我将存储层与 User 类分开,以访问进一步调用任何自定义 DAL 的方法集合。
在 DAL 实现中使用 static
是否正确?
请提出更正或我可以做得更好的方法。我没有太多分层编写代码的经验。
I have the following Data Access Layer (DAL). I was wondering if it's set up correctly, or if I need to improve it?
public class User
{
}
//Persistence methods
static class UserDataAccess
{
UsersDAL udal = // Choose SQL or FileSystem DAL impl.
InsertUser(User u)
{
// Custom logic , is 'u' valid etc.
udal.Insert(u);
}
}
abstract class UsersDAL
{
GetUserByID();
InsertUser(u);
...
}
// implementaitons of DAL
static class UsersSQLStore : UsersDAL
{
}
static class UsersFileSystemStore : UsersDAL
{
}
I separated the storage layer from the User class to access methods collection which further call any custom DAL.
Is use of static
in DAL implementation correct?
Please suggest corrections or ways I can make this better. I don't have a lot of experience with writing code in layers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些类都不应该是静态的。我认为您也不应该将类命名为
DAL
,因为它是数据访问层的缩写,并且类本身并不是一个层(至少在我看来)。您可以使用广泛采用的术语存储库。我建议您执行如下操作:请注意,
UserService
在其构造函数中注入了抽象类UserRepository
的实例。您可以使用依赖注入 (DI) 框架自动为您执行此操作,例如 Windsor Castle来自城堡项目。它将允许您在配置文件或代码中指定从抽象(UserRepository
)到具体实现(例如SqlUserRepository
)的映射。希望这能为您指明正确的方向,如果您需要更多信息,请询问。
None of those classes should be
static
. I don't think you should name your classesDAL
either, because its short for Data Access Layer, and a class in itself is not a layer (in my mind at least). You can use the widely adopted term repository instead. I suggest you do something like the following:Note that the
UserService
is injected with an instance of the abstract classUserRepository
in its constructor. You can use a Dependency Injection (DI) framework to do this for you automatically, such as Windsor Castle from Castle Project. It will allow you to specify a mapping from abstraction (UserRepository
) to concrete implementation (eg.SqlUserRepository
) in a configuration file, or in code.Hope this points you in the right direction, and please ask if you need more information.
我的拙见
My Humble Opinions
Davy Brion 在这个主题上有一组优秀的博客文章:位于 GitHub
Davy Brion has an excellent set of blog posts on this subject: located on GitHub