I am trying to pass an interface and settings into a class while creating an instance of that class in startup.cs in .Net Core Project. I am using the below code to do so. I have some code written in the constructor of Student class but while starting the application the Code/Logic inside the constructor is not working. There is no error but the debug pointer is not hitting the constructor of Student class.
services.AddSingleton(c => new Student(settings, resourceSetting, c.GetService<IPersonService>()));
If I am using the below code then the code inside Student constructor is working fine.
Student studentHandler = new Student(settings, resourceSetting,);
services.AddSingleton<Student>(studentHandler);
But I need to pass Service interface in the constructor to do some work while starting the Project. Can anyone help me with what I am missing here?
That's because you're registering the type as an implementation factory in the first snippet, using
AddSingleton<TService> (this IServiceCollection services, Func<IServiceProvider,TService> implementationFactory)
With this method, the implementation factory delegate (and subsequently theStudent
constructor) won't be called until the dependency is resolved.In the second snippet, you're directly instantiating the type at service registration and adding that instance to the service collection with
AddSingleton<TService> (this IServiceCollection services, TService implementationInstance)
.Here's an example with logs explaining each step in each approach:
The output of this is:
With this you can clearly see that when registering using the factory delegate, the
Student
constructor isn't called until the type is resolved (withGetService<Student>()
in this case).