Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created April 27, 2021 17:11
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/1e00bce418078fc9554e48ffd87efa46 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/1e00bce418078fc9554e48ffd87efa46 to your computer and use it in GitHub Desktop.
Index action and view are modified in HomeController to use lazy dependency
// HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly Lazy<ICreatedOnDateTimeService> lazyService;
public HomeController(ILogger<HomeController> logger, Lazy<ICreatedOnDateTimeService> lazyService)
{
_logger = logger;
this.lazyService = lazyService;
}
public IActionResult Index([FromQuery]bool create = false)
{
ViewData["IsValueCreated"] = this.lazyService.IsValueCreated;
if (create)
{
ViewData["CreatedOn"] = this.lazyService.Value.CreatedOn;
}
return View();
}
}
// Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about delayed instantiation with .NET dependency injection</p>
<div class="card" style="margin-top:2rem; width: 40rem">
<div class="card-header">
Created On Time
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item text-left"><strong>Dependency.IsValueCreated:</strong> @ViewData["IsValueCreated"]</li>
<li class="list-group-item text-left"><strong>Dependency.Value.CreatedOn:</strong> @ViewData["CreatedOn"]</li>
</ul>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment