I am going to make up an example here just to get my point across. Please consider the following class:
public class MovieController : Controller
{
private readonly IMovieService _movieService;
private readonly IUserService _userService;
public MovieController(IMovieService movieService, IUserService userService)
{
_movieService = movieService;
_userService = userService;
}
public ViewModel GetMovies()
{
return View("Movies", _movieService.GetMovies());
}
public ViewModel GetAuthors()
{
return View("Authors", _userService.GetAuthors());
}
}
With the example above, whenever the MovieController is created, it will create both services. Each service will require its services and repositories in the constructor. So, in reality, I may be creating some classes each time MovieController is called. For this reason, I want to implement Lazy loading as I believe it will improve performance. For this reason, please consider the next class:
public class MovieController : Controller
{
private readonly IMovieService _movieService;
private readonly IUserService _userService;
private MovieService
{
get
{
if (_movieService == null) _movieService = new MovieService();
return _movieService;
}
}
private UserService
{
get
{
if (_userService == null) _userService = new UserService();
return _userService;
}
}
public MovieController() { }
public ViewModel GetMovies()
{
return View("Movies", MovieService.GetMovies());
}
public ViewModel GetAuthors()
{
return View("Authors", UserService.GetAuthors());
}
}
The problem with the above example is that I lost DI. Now I understand the benefit of DI, and I very much want to keep it, and as such, I came up with the following example:
public class MovieController : Controller
{
private readonly IMovieService _movieService;
private readonly IUserService _userService;
private MovieService
{
get
{
if (_movieService == null) _movieService = DependencyResolver.Current.GetService(typeof(IMovieService));
return _movieService;
}
}
private UserService
{
get
{
if (_userService == null) _userService = DependencyResolver.Current.GetService(typeof(IUserService));
return _userService;
}
}
public MovieController() { }
public ViewModel GetMovies()
{
return View("Movies", MovieService.GetMovies());
}
public ViewModel GetAuthors()
{
return View("Authors", UserService.GetAuthors());
}
}
Is my third example in this question a bad practice? If so, why? Am I losing on performance by doing this or is there another reason why this would be considered bad practice?
Aucun commentaire:
Enregistrer un commentaire