Home > Blockchain >  C# How to instantiate new object with Dependency Injection
C# How to instantiate new object with Dependency Injection

Time:02-11

I have a class that is using Logger:

internal class Class1
{
    private readonly ILogger<Class1> _logger;
    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }
    internal void Method1()
    {
        //some code
    }
}

When I try using it, the compiler correctly tells me that there is no constructor that matches this signature:

Class1 cl1 = new Class1();

I want to use default constructor. If I understand this correctly, Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class. How do I do that?? Thank you for your help.

CodePudding user response:

you have to DI to the program code if you are using net 6 (or startup if you don't use program)

.....

builder.Services.AddScoped(typeof(Class1));

var app = builder.Build();
....

if youi try to use this way

Class1 cl1 = new Class1();

you will have to have parameterless construtor

internal Class1()
{
        _logger = ... tons of code to create a logger instance
}

or may be (I don't know where are you creating the instance of class)

var logger= .. tons of code to create a logger instance
var cl1 = new Class1(logger);

CodePudding user response:

You state, "I want to use default constructor. ... Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class. How do I do that?"

To do what you are asking,

internal class Class1
{
    private readonly ILogger<Class1> _logger;

    // This constructor will pass to the constructor with the matching 
    // signature and it will pass a new instance of the Logger<Class1> class.
    // But in using this approach you will be bypassing the DI, which may be
    // what you need in some cases, but you should still be aware of what is happening
    internal Class1() : this(new Logger<Class1>())
    {
    }

    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }    

    internal void Method1()
    {
        //some code
    }
}
  • Related