service lifetime

 avatar
unknown
csharp
a year ago
2.3 kB
5
Indexable
namespace Services
{
    public class RestaurantService : IRestaurantService
    {
        private readonly ITeaService _teaService;
        public RestaurantService(ITeaService teaService)
        {
            _teaService = teaService;
        }

        public string GetTea()
        {
            return _teaService.GetTea();
        }
    }

    public interface IRestaurantService
    {
        string GetTea();
    }
}

namespace LearnWebAPI.Services
{
    public class TeaService : ITeaService
    {
        private readonly int _randomId ;
        private readonly Dictionary<int, string> _teaDictionary = new()
        {
            { 1, "Normal Tea ☕️" },
            { 2, "Lemon Tea ☕️" },
            { 3, "Green Tea ☕️" },
            { 4, "Masala Chai ☕️" },
            { 5, "Ginger Tea ☕️" }
        };
        public TeaService()
        {
            _randomId = new Random().Next(1, 5);
        } 
        public string GetTea()
        {
            return _teaDictionary[_randomId];

        }
    }
    public interface ITeaService
    {
        string GetTea();
    }
}



[Route("api/[controller]")]
[ApiController]
public class TeaController : ControllerBase
{
  private readonly ITeaService _teaService;
  private readonly IRestaurantService _restaurantService;

  public TeaController(ITeaService teaService,
   IRestaurantService restaurantService)
  {
      _teaService = teaService;
      _restaurantService = restaurantService;
   }

   [HttpGet]
   public IActionResult Get()
   {
      var tea = _teaService.GetTea();
      var teaFromRestra = _restaurantService.GetTea();
      return Ok($"From TeaService : {tea}
               \nFrom RestaurantService : {teaFromRestra}");
    }
}


Program.cs

            //1. Transient

            services.AddTransient<ITeaService, TeaService>();
            services.AddTransient<IRestaurantService, RestaurantService>();

            //2. Scope

            //services.AddScoped<ITeaService, TeaService>();
            //services.AddScoped<IRestaurantService, RestaurantService>();

            //3. Singleton

            //services.AddSingleton<ITeaService, TeaService>();
            //services.AddSingleton<IRestaurantService, RestaurantService>();

Editor is loading...
Leave a Comment