我的存储库方法不应该是静态的有什么原因吗?

发布于 2024-11-30 23:35:41 字数 459 浏览 1 评论 0原文

我一直在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吃兔兔 2024-12-07 23:35:41

好吧,如果您不打算解耦、测试和轻松维护您的“存储库”,我想静态就可以了。

如果您想详细了解为什么静态方法被视为代码异味,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!

我ぃ本無心為│何有愛 2024-12-07 23:35:41

当您需要存储库的多个实例时,您可能无法这样做。此外,如果方法是静态的,您可能无法使用依赖注入。

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 2024-12-07 23:35:41

我不鼓励在存储库中使用静态方法。其一,您不能在存储库中使用依赖项注入,因为注入的依赖项在静态方法中不可用,仅在实例方法中可用。测试将会很困难。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文