简体   繁体   中英

How can I code a class constructor in a class that inherits from a base class where the base class needs a service injected?

Can anyone give me some advice. I am using

Microsoft.Extensions.DependencyInjection version 5.0.1 nuget package

I have many different views that are all based on LogBase. In logBase there are properties that are set and so I need to inject in the ConfigService:

public class LogViews : LogBase
{
    public LogViews()
    {
        //
    }
    //
}

public class LogBase
{
    private readonly IConfigService _configService;
    public LogBase(IConfigService configService)
    {
        _configService = configService;
        X = _configService.X;
    }
}

But when the code runs it gives an error here public LogViews() as it is trying to call the LogBase constructor which needs the configService argument.

Does anyone have an idea how I can solve this DI problem?

You should define the parametrized constructor of LogViews which should have IConfigService instance being injected. The same can be passed to base constructor as shown below

public class LogViews : LogBase
{
    public LogViews(IConfigService configService) : base(configService)
    {
        //
    }
    //
}

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