Friday, 29 April 2016

c# - Constructor Dependency injection in asp.net core 2





I have read this official documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection.



There is something i do not understand in constructor injection:



Let's have a look to my code, which works fine:




public class HomeController : Controller
{
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;
private readonly RoleManager _roleManager;

public HomeController(
SignInManager signInManager,
UserManager userManager,

RoleManager roleManager)
{
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
}


It works fine too if change constructor parameter orders or if i remove some parameters like this:




public class HomeController : Controller
{
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;

public HomeController(
UserManager userManager
SignInManager signInManager,
)
{

_userManager = userManager;
_signInManager = signInManager;
}


I have understood the concept of DI. What i do not understand is how does it works in C# to have something dynamic in constructor parameters ?
Is there a set of all kind of overload constructors ?



Thanks


Answer





how does it work in C# to have something dynamic in constructor parameters ? Is there a set of all kind of overload constructors?




Don't use "dynamic" like that, it's a buzzword in that sentence. In programming, everything is dynamic.



If you mean to ask how a DI framework can match up registered services with constructor parameters, then yes, there is a set of constructor overloads.



The DI framework finds these through reflection, see MSDN: Type.GetConstructors(). Then for each constructor, the framework obtains the parameters of each constructor, matches those up with the registered services and invokes one of the constructors.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...