locked
Injecting Services into Controllers RRS feed

  • Question

  • User-305496339 posted

    Hi Friends,

    I was wondering how I would inject a service into a controller? Thanks !!!

    Wednesday, January 6, 2021 7:40 PM

Answers

  • User-2054057000 posted

    I was wondering how I would inject a service into a controller? Thanks !!!

    Through Dependency Injection (DI) - Dependency Injection in ASP.NET Core

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 7, 2021 5:10 AM
  • User1686398519 posted

    Hi rkrex, 

    1. You need to register the new IMyService implementation in the Starp file.
      • public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IMyService,MyService>();
        }
    2. Then,you can use it like this:
      •  public class HomeController : Controller
            {
                private readonly IMyService _myservice;
                public HomeController(IMyService myservice)
                {
                    _myservice=myservice; 
                }
        public IActionResult Index(){
        _myservice.Add();
        return View();
        } }

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 7, 2021 6:28 AM

All replies

  • User475983607 posted

    I would start by reading the official docs.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0

    Wednesday, January 6, 2021 8:06 PM
  • User-2054057000 posted

    I was wondering how I would inject a service into a controller? Thanks !!!

    Through Dependency Injection (DI) - Dependency Injection in ASP.NET Core

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 7, 2021 5:10 AM
  • User1686398519 posted

    Hi rkrex, 

    1. You need to register the new IMyService implementation in the Starp file.
      • public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IMyService,MyService>();
        }
    2. Then,you can use it like this:
      •  public class HomeController : Controller
            {
                private readonly IMyService _myservice;
                public HomeController(IMyService myservice)
                {
                    _myservice=myservice; 
                }
        public IActionResult Index(){
        _myservice.Add();
        return View();
        } }

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 7, 2021 6:28 AM