我的存储库方法不应该是静态的有什么原因吗?
我一直在使用 MVC 应用程序并创建用于操作、验证、更新和读/写数据的存储库。它们都是静态的。这是一个例子:
public static int Create(user u)
{
using(DataContext db = new DataContext())
{
//do the thing and submit changes...
}
//return the new user id
}
(注意:这只是一个示例,我并不是在寻找有关创建的提示 用户或返回用户 ID 等)
然后我可以调用 int id = RepoClassName.Create(userVariable);
使用这样的静态方法有什么问题吗?我只是不明白为什么我需要实例化一个对象来执行此操作。
I have been working with an MVC app and creating Repositories that manipulate, validate, update, and read/write data. All of them are static. Here is an example:
public static int Create(user u)
{
using(DataContext db = new DataContext())
{
//do the thing and submit changes...
}
//return the new user id
}
(Note: this is just a sample, I am not looking for tips about creating
users or returning user ids, etc.)
Then I can just call int id = RepoClassName.Create(userVariable);
Is there anything wrong with using static methods like this? I just don't see why I should need to instantiate an object to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,如果您不打算解耦、测试和轻松维护您的“存储库”,我想静态就可以了。
如果您想详细了解为什么静态方法被视为代码异味,Google 测试博客上有一篇不错的文章。当然,这是假设您完全关心测试代码。
但是,嘿,现在是 2011 年了,谁不想呢!
Well if you don't intend to decouple, test, and easily maintain your "repository", I guess static is just fine.
If you want to know more about why static methods are considered a code smell, here's a nice article at the Google Testing Blog. This, of course, assumes that you care about testing your code at all.
But hey, it's 2011, who wouldn't!
当您需要存储库的多个实例时,您可能无法这样做。此外,如果方法是静态的,您可能无法使用依赖注入。
May be down the line when you need multiple instances of repository, you may not be able to do so. Also you may not be able to use Dependency Injection if the methods are static.
我不鼓励在存储库中使用静态方法。其一,您不能在存储库中使用依赖项注入,因为注入的依赖项在静态方法中不可用,仅在实例方法中可用。测试将会很困难。
I wouldn't encourage the use of static methods in your repository. For one, you cannot use dependency injection with your repositories, because the injected dependencies aren't available in the static methods, only in instance methods. Testing wil be difficult.