Rasmus Hansen
Rasmus Hansen

Reputation: 43

Pass parameter when initialising Dependency Injection in ASP.NET core

I have a simple class which looks like this:

public class TestClass1
{
    private string testString = "Should be set by DI";

    public TestClass1(string testString)
    {
        this.testString = testString;
    }
    public string GetData()
    {
        return testString + DateTime.Now;
    }
}

I want to inject it using the build-in DI in a simple ASP.NET core web app, but with the "testString" parameter set when initialising the Dependency Injection.

I've tried setting the following in startup.cs but it fails at runtime because TestClass1 doesn't have a parameterless constructor:

services.AddScoped(provider => new TestClass1("Success!")); 

Upvotes: 4

Views: 4341

Answers (1)

Tseng
Tseng

Reputation: 64288

I suspect you just missed the cruical part of the code and your usage of the DI is just plain wrong, not the registration.

public class MyController 
{
    private readonly MyClass myClass;

    public MyController()
    {
        // This doesn't work and do not involve DI at all
        // It will fail because MyClass has no parameterles constructor
        this.myClass = new MyClass(); 
    }
}

The above won't work, because DI is no compiler magic that let you magically inject dependencies when calling new on the type.

public class MyController 
{
    private readonly MyClass myClass;

    public MyController(MyClass myClass)
    {
        // This should work, because the IoC/DI Container creates the instance
        // and pass it into the controller
        this.myClass = myClass;
    }
}

When you use DI/IoC you let the constructor generate and instantiate the objects, hence you never call new in your service classes. Just tell in the constructor that you need an instance of some type or it's interface.

Edit:

This used to work in previous versions (betas) of ASP.NET Core. Should still work, but limited to parameters:

public class MyController 
{
    public IActionResult Index([FromServices]MyClass myClass)
    {
    }
}

Upvotes: 1

Related Questions