Search code examples
c#dependency-injectionasp.net-core-mvc-2.0

How do I configure mvc core 2 dependency injection with parameters, where one of the parameters is a dependency?


If I have:

public CatManager(ICatCastle catCastle, int something)

I want to set this up to be dependency injected, but I am not sure how.

I think I can do this:

services.AddScoped<ICatCastle, CatCastle>();

services.AddScoped<ICatManager>(new CatManager(???, 42));

But I am not sure what to put in as the ??? to get the CatCastle. I'd like it to resolve a new CatCastle every time CatManager is injected.

As a further step, I wonder if it possible to do something like:

public CatManager(int something)

services.AddScoped<ICatManager>(new CatManager(ResolveICatCastleIntoCatCastle().SomeID));

So that CatManager's constructor is automatically invoked with the ID, but not the object that gets the IDs. For example, if it is a database connection I want that resolution to occur when it is created and not later on when the property is actually accessed.


Solution

  • You can use the factory delegate overload.

    Like

    services.AddScoped<ICatManager>(serviceProvider => 
        new CatManager(serviceProvider.GetRequiredService<ICatCastle>(), 42));
    

    I'd like it to resolve a new CatCastle every time CatManager is injected.

    If you want a new castle then you need to register CatCastle with a transient scope

    services.AddTransient<ICatCastle, CatCastle>();
    

    Regarding the further step public CatManager(int something), a similar approach can be done

    services.AddScoped<ICatManager>(serviceProvider => 
        new CatManager(serviceProvider.GetRequiredService<ICatCastle>().SomeID));
    

    where the dependency is resolved and what ever action is performed before injecting it into the dependent class.