Hi @Biris, Aris (Μπίρης Άρης) ,
When use Dependency injection in ASP.NET Core, after creating the service with/without the interface, we need to register the service with a lifetime in the ConfigureServices method (use the AddScoped(), AddTransient() and AddSingleton() method), like this:
namespace Core3_1MVC.Services
{
public class Service1
{
public string GetAllStudent()
{
return "Students";
}
}
public class Service2:IDisposable
{
private bool _disposed;
public void Dispose()
{
if (_disposed)
return;
Console.WriteLine("Service2.Dispose");
_disposed = true;
}
public string GetAllStudent()
{
return "Students";
}
}
public interface IService3Interface
{
string GetAllStatus();
}
public class Service3 : IService3Interface
{
public string GetAllStatus()
{
return "Status";
}
}
}
Code in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<Service1>();
services.AddScoped<Service2>();
services.AddScoped<IService3Interface, Service3>();
services.AddControllersWithViews();
}
Then, access the services in the controller:
public class HomeController : Controller
{
private readonly IService3Interface _service3;
private readonly Service1 _service1;
private readonly Service2 _service2;
public HomeController(IService3Interface service3Interface, Service1 service1, Service2 service2)
{
_service3 = service3Interface;
_service1 = service1;
_service2 = service2;
}
public IActionResult Index()
{
var result1 = _service1.GetAllStudent();
var result2 = _service2.GetAllStudent();
var result3 = _service3.GetAllStatus();
return View();
}
More detail information, see:
Dependency injection in ASP.NET Core
Dependency injection into controllers in ASP.NET Core
Dependency injection into views in ASP.NET Core
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion