Kunal Patel Kunal Patel - 1 month ago 12
C# Question

ASP.NET Core MVC FromService binding in Controller returns empty collection

Been trying to get a grip of ASP.NET Core MVC but got stuck with dependency injection returning empty collection in my controller action, despite of registering the service as Singleton in

ConfigureService
method. Tried two different ways to register but only one of them actually works. Said method is as following:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
/***THIS DOES NOT WORK***/
services.AddSingleton<IRepository<Employee>, EmployeeRepository>();
var empRepo = services.BuildServiceProvider().GetService<IRepository<Employee>>();
empRepo.Create( "emp001" );

/***THIS WORKS***/
var employeeRepository = new EmployeeRepository();
employeeRepository.Create( "emp001" );
services.AddSingleton<EmployeeRepository>( employeeRepository );
}


And following is my Controller action:

[HttpGet( "{empID}" )]
public string GetEmployee( string empID, [FromServices] IRepository<Employee> employees **/*THIS IS ALWAYS EMPTY*/**)
{
....
}


Kindly point me in the right direction. What is the difference between the two
AddSingleton
methods? How can I access the service using 1st approach by DI on Controller action? TIA.

Answer

I had to fall back to the only working option for me which is what @Daniel J.G. suggested to use; the AddSingleton<T>() after having initialised the repository (along with some useful tips from him). Though, I would have liked to have the other option work after initialisation.