MVC 对象实例还是静态类?
我对何时创建对象实例或静态帮助器类感到困惑。 例如,如果我调用一个方法来更新数据模型并提交到数据库,我将创建一个 DataContext 实例。 该 Datacontext 的生命周期是多少?每次需要新数据更新时是否可以创建新实例?
在我的控制器中,我创建了一个 DataCOntext 实例,并在回发到控制器时重用该实例。
I am confused as to when to create object instances or Static Helper classes. For example, if I call a method to update a data model and submit to database, i create an instance of the DataContext. What is the lifetime of that Datacontext and is it ok to create new instances every time there needs to be a new data updates?
In my controller I created an instance of DataCOntext and reuse that instance when posting back to controller for example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataContext 是一个非常轻量级的类,旨在用于工作单元。 通常,我传入一个工厂,该工厂将根据需要创建适当的 DataContext。 我通常会将其包装在 using 块中并将结果转换为列表(或其他对象),以便在控制器代码中执行查询并将结果对象传递到我的视图。 这样,可以在控制器方法中处置 DataContext(从 using 块)。
将工厂注入控制器的原因有两个:它允许按需创建 DataContext,并且允许我使用生成模拟 DataContext 的工厂进行测试。 后者允许我避免在单元测试中使用实际的数据库。
The DataContext is a pretty lightweight class and is intended to be used for a unit of work. Typically, I pass in a Factory that will create an appropriate DataContext as needed. I will usually wrap this in a using block and convert the results to a List (or other object) so that the query is performed in the controller code and the resulting objects passed to my view. This way the DataContext can be disposed of (from the using block) in the controller method.
The reason that inject a factory into the controller is two-fold -- it allows the DataContext to be created on demand and it allows me to use a factory that generates a mock DataContext for testing. The latter allows me to avoid using the actual database in my unit tests.