PRACTICAL 9.1: SERVICE APPLICATION (DEPENDENCY INJECTION)

STEPS:
1. Create an ASP.NET Core Web Application (MVC) project (Pracs).
2. In Solution Explorer create a folder "Services".
3. In the Services folder add an interface IWeatherServices and a class WeatherServices.
4. In HomeController.cs inject IWeatherServices through the constructor and call it in Index().
5. In Views > Home > Index.cshtml display the alert message.
6. In Startup.cs register the service in ConfigureServices.
7. Run the project.

CODE: (Services/IWeatherServices.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pracs.Services
{
    public interface IWeatherServices
    {
        string GetWeatherAlert();
    }
}

CODE: (Services/WeatherServices.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pracs.Services
{
    public class WeatherServices:IWeatherServices
    {
        public string GetWeatherAlert()
        {
            return "Heavy rainfall expected Tommorow.pack an Umbrella.";
        }
    }
}

CODE: (Controllers/HomeController.cs)
using Pracs.Services;

namespace Pracs.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IWeatherServices _weatherService;

        public HomeController(ILogger<HomeController> logger,IWeatherServices weatherService)
        {
            _logger = logger;
            _weatherService = weatherService;
        }

        public IActionResult Index()
        {
            string alertMessage = _weatherService.GetWeatherAlert();
            ViewData["Alert"] = alertMessage;
            return View();
        }
    }
}

CODE: (Views/Home/Index.cshtml)
@{
    ViewData["Title"] = "Home Page";
}

<h2>Weather Alert</h2>
<p>@ViewData["Alert"]</p>

CODE: (Startup.cs - ConfigureServices)
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IWeatherServices, WeatherServices > ();
    services.AddControllersWithViews();
}

OUTPUT:
The Home page shows "Weather Alert" and the message:
Heavy rainfall expected Tommorow.pack an Umbrella.
