1

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<Utilisateurs> _userManager;
    private readonly SignInManager<Utilisateurs> _signInManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public HomeController(
        SignInManager<Utilisateurs> signInManager,
        UserManager<Utilisateurs> userManager,
        RoleManager<IdentityRole> 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<Utilisateurs> _userManager;
    private readonly SignInManager<Utilisateurs> _signInManager;

    public HomeController(
        UserManager<Utilisateurs> userManager
        SignInManager<Utilisateurs> 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

Cake or Death
  • 7,895
  • 4
  • 32
  • 45
Bob5421
  • 6,002
  • 10
  • 44
  • 120
  • 1
    You need to clarify your question. What do you mean by `have something dynamic in constructor parameters`? Are you referring to the `dynamic` key word? – Nkosi Nov 30 '17 at 09:36
  • Might help to look at what a really simple [hand-rolled](https://stackoverflow.com/questions/15715978/simple-dependency-resolver#15717047) DI implementation actually does - nothing particularly clever is required. Obviously fully-fledged DI frameworks are more evolved, but at their core, they are just doing the same thing. – Cake or Death Nov 30 '17 at 09:56

1 Answers1

2

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.

CodeCaster
  • 131,656
  • 19
  • 190
  • 236