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!"));
new TestClass()? DI doesn't work like thisnewkeyword when obtaining an instance. You always inject it via constructor. DI is not some compiler magic, it's just plain CLR/OOP with a bit of reflection or ExpressionTrees. I suspect he doesnew TestClass()in his code (notice the new keyword and no parameter). That's not how DI works. Rather you pass it via constructor likepublic MyService(TestClass injectedTestCass)