Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created April 23, 2021 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/5695a572fb9d18742a00d7c51745867f to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/5695a572fb9d18742a00d7c51745867f to your computer and use it in GitHub Desktop.
Dependency Injection and Basic Terminology
// Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICustomLogger, CustomLogger>();
services.AddScoped<IRepository, Repository>();
services.AddControllersWithViews();
}
}
// HomeController.cs
public class HomeController : Controller
{
private readonly ICustomLogger _logger;
private readonly IRepository _repository;
public HomeController(ICustomLogger logger, IRepository repository)
{
_logger = logger;
_repository = repository;
}
public IActionResult Index()
{
// Load data from repository
ViewData["DataCollection"] = repository.GetData();
_logger.Log("data retrieved successfully");
return View();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment