Rasik
Rasik

Reputation: 2410

dependency injection with multiple class constructor

I have the class as:

public class ServiceUtility
{
    private IHostingEnvironment _environment;
    public ServiceUtility(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public string GetFilePath(string fileName)
    {
        return _environment.WebRootFileProvider.GetFileInfo(fileName)?.PhysicalPath;
    }
}

Using in Startup.cs

services.AddScoped<ServiceUtility>();

Using ServiceUtility in another class:

public class LevelUp
{
        private readonly ServiceUtility _serviceUtility;
        public LevelUp(ServiceUtility serviceUtility)
        {
            _serviceUtility = serviceUtility;
        }
        public LevelUp(string input)
        {
          //here the _serviceUtility is null
        }
        public int UserId { get; set; }
        public int Level { get; set; }
}

From controller I am using as:

var object = userList.Select(x => new LevelUp(x.Description));

When I am using the _serviceUtility in Levelup(string input) constructor, the value is always null.

I have also added in Startup.cs class:

services.AddScoped<LevelUp>();

What I am doing wrong here, what is the proper way of dependency injection with multiple constructors?

Upvotes: 1

Views: 1961

Answers (1)

Steven
Steven

Reputation: 172606

In your controller you are (manually) calling the LevelUp constructor with the string parameter (ctor(string)) and not the ctor(ServiceUtility) constructor. This LevelUp class is not created by the DI Container, you are creating it yourself. If you wish to supply ServiceUtility to LevelUp, you should pass both the string and ServiceUtility through the same constructor:

public class LevelUp
{
    private readonly ServiceUtility _serviceUtility;

    public LevelUp(ServiceUtility serviceUtility, string input)
    {
        _serviceUtility = serviceUtility;
    }

    public int UserId { get; set; }
    public int Level { get; set; }
}

From within your controller you then have to pass ServiceUtility as well to LevelUp's constructor:

public class HomeController : Controller
{
    private readonly ServiceUtility serviceUtility;

    public HomeController(ServiceUtility serviceUtility)
    {
        this.serviceUtility = serviceUtility;
    }

    public object Index(List userList)
    {
        var object =
            userList.Select(x => new LevelUp(this.serviceUtility, x.Description));
    }
}

Upvotes: 2

Related Questions