Where should 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 class member?
public class UserController : Controller
{
private UnitOfWork unitofwork = new UnitofWork();
public ActionResult DoStuff(){
...
It's personal preference, really. Some people prefer to initialize outside of the constructor simply because there's less of a chance of someone else coming along and adding a new member without initializing it, since there's an example right in front of them.
As a general rule, if the initialization of an object requires any logic or requires parameters, then I prefer to do it in the constructor. Whatever you choose, though, make sure to remain consistent.
EDIT: Note, initializing in the constructor also allows you make calls to non-static methods and properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With