gog
gog

Reputation: 12988

Correct way to use static methods in Web application

I have a web application with the repository layer and the WebUI layer.

Basically i fill some grids with data that i get from this repository dll. Actually im doing like this:

private DemoRepository _demoRepository;

public DemoController()
{
    _demoRepository = new DemoRepository();
}

public ActionResult Demonstration()
{
     return View(_demoRepository.GetAll());
}

My question is, actually i dont need to create an object everytime so i could make the DemoRepository static and call directly in the ActionResult method:

public ActionResult Demonstration()
{
     return View(DemoRepository.GetAll());
}

But otherwise i know that its not a good practice to use static variables in web application, but in this case that im executing a method to get some data, is it correct?

Upvotes: 0

Views: 557

Answers (1)

Nathan R
Nathan R

Reputation: 1240

A static method won't hurt as long as that static method receives all dependencies in the method call as parameters and isn't changing anything globally for the repository inside the method call.

If you're going to violate one of these two things (ie: DI via properties or some magic with connection strings), then I would stick with instantiating the repository and calling its GetAll() method.

Upvotes: 1

Related Questions