I understand how I can register dependencies for ASP.NET core and how constructor injection works for my controllers (I have that working). Does everything have to get passed through constructors and then explicitly down to objects created by those constructed objects, or how do the objects that get instantiated, such as my controllers, and the objects that they create, use the service collection to access or instantiate additional objects?
Update 19.June.2020:
So let's say my Startup calls this (this is just sample code to see if I can get this question and hence my account unbanned):
public static IServiceCollection AddRepository(
this IServiceCollection services,
IConfiguration configuration)
{
var serviceProvider = services.BuildServiceProvider(); //TODO: dispose
ContentstackClient stack = serviceProvider.GetService<ContentstackClient>();
Trace.Assert(stack != null, "configure ContentstackClient service before IRepository service");
IConfigureSerialization configurator = serviceProvider.GetService<IConfigureSerialization>();
Trace.Assert(configurator != null, "configure IConfigureSerialization before ContentstackRepository");
configurator.ConfigureSerialization(stack.SerializerSettings);
//TODO: Apply ContentstackRepositoryConfiguration (UseSync, etc.) from appsettings.json
ContentstackRepositoryConfiguration repoConfig = ContentstackRepositoryConfiguration.Get(
ContentstackRepositoryConfiguration.StartType.FastestStartSync, stack);
services.AddSingleton<IRepository>(new ContentstackRepository(repoConfig));//, serviceProvider.GetService<ILogger>()));
//TODO: happens automatically? serviceProvider.Dispose();
return services;
}
I have this in my controller:
public EntryController(
IRepository repository,
ILogger<EntryController> logger,
ContentstackClient stack)
{
_repository = repository;
_logger = logger;
_stack = stack;
}
But what if code in my view or elsewhere wants to access the IRepository singleton? Do I have to pass the IRepository all over the place, or is there some way to access it explicitly through a service locator or something?