简体   繁体   中英

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?

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM