Asp.net MVC4, C # Create an instance of an object

Where can I create an instance? which way is better and why?

1) In the constructor?

public class UserController : Controller
{
    private UnitOfWork unitofwork;

    public UserController(){
         unitofwork = new UnitofWork();
    }

    public ActionResult DoStuff(){
    ...

2) as a private member of the class?

public class UserController : Controller
{
    private UnitOfWork unitofwork = new UnitofWork();

    public ActionResult DoStuff(){
    ...
+5
source share
3 answers

This is a personal preference, really. Some people prefer to initialize outside the constructor simply because there is less chance that someone else will appear and add a new member without initializing it, since there is an example right in front of them.

As a rule, if the initialization of an object requires any logic or requires parameters, then I prefer to do this in the constructor. Whatever you choose, make sure you stay the same.

EDIT: .

+1

, . , , .

( ).

0

I prefer to store it in the constructor, as it allows you to extend it by line, if necessary, without updating all the locations that caused it to be called, and also makes your calling code more understandable and more concise.

0
source

All Articles