将数据库初始化调用放在C#构造函数中可以吗? [英] Is it OK to put a database initialization call in a C# constructor?

查看:88
本文介绍了将数据库初始化调用放在C#构造函数中可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到这是各种各样的代码库,并且想知道它是否普遍不受欢迎。

I've seen this is various codebases, and wanted to know if this generally frowned upon or not.

例如:

public class MyClass
{
   public int Id;

   public MyClass()
   {
      Id = new Database().GetIdFor(typeof(MyClass));
   }
}


推荐答案

有有几个原因导致人们普遍认为这种设计不被认为是好的设计,其中一些已经引起了难以进行的单元测试和错误处理的困难。

There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned.

我选择不这样做的主要原因这样做是因为您的对象和数据访问层现在已经非常紧密地耦合在一起,这意味着在原始设计之外对该对象的任何使用都需要大量的返工。例如,如果遇到一个实例,在该实例中您需要使用该对象而未分配任何值来持久化该类的新实例,该怎么办?现在,您要么必须重载构造函数,然后确保所有其他逻辑都能处理这种新情况,要么继承并重写。

The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that any use of that object outside of it original design requires significant rework. As an example what if you came across an instance where you needed to use that object without any values assigned for instance to persist a new instance of that class? you now either have to overload the constructor and then make sure all of your other logic handles this new case, or inherit and override.

如果对象和数据访问已分离,则可以创建一个实例,然后对其进行混合处理。或者,如果您有使用相同实体但使用不同持久层的其他项目,则这些对象是可重用的。

If the object and the data access were decoupled then you could create an instance and then not hydrate it. Or if your have a different project that uses the same entities but uses a different persistence layer then the objects are reusable.

说过,我过去在项目中采用了更简单的耦合方式:)

Having said that I have taken the easier path of coupling in projects in the past :)

这篇关于将数据库初始化调用放在C#构造函数中可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆