![](/img/trans.png)
[英]c# class inherits from base class with constructor with dependency injection
[英]Why does a C# class which inherits from ServiceBase skip its derived class constructor?
问题
当我实例化 Service 类的一个实例时 - 派生自 ServiceBase 类 - 在实例化过程中会跳过我为 Service 类创建的构造函数。 然后,当“private ServiceController controller...”这一行被击中时,它会失败,因为 ConfigStream 对象从未传递给服务类变量 _configstream。 我没有在代码中的其他地方跳过构造函数的问题。 这与基类ServiceBase 的使用有关吗?
我试过包括基类构造函数,如:
public Service(ConfigStream configstream) : base() {}
它不会产生任何不同的结果。 从我读过的内容来看,这是有道理的,因为默认情况下应该调用基类的默认构造函数。
我已经包括了我的服务类和 ConfigStream 的开头。 ConfigStream 使用它的构造函数没有任何问题,但它也没有继承任何类。
代码
public static class MainClass
{
static void Main(String[] args)
{
// Test if input arguments were supplied
if (args.Length > 0)
{
// if arguments supplied, use the supplied config file path (second cli argument)
if (args[0] == "-i")
{
// ConfigStream configstream = new ConfigStream(args[1]);
ServiceBase.Run(new Service(new ConfigStream(args[1])));
}
}
else
{
// otherwise run service without arguments
// the config will be assumed in the same directory
Service service = new Service(new ConfigStream());
ServiceBase.Run(service);
}
}
}
public class Service : ServiceBase
{
// class instantiation
private Thread processThread;
private Process process;
// Instance variables
private static ConfigStream _configstream;
// Function: Service
// Purpose: Class Constructor
public Service(ConfigStream configstream)
{
// assign ConfigStream instance
_configstream = configstream;
// set global service name and description for use by installer
GlobalVariables.setServicename(_configstream.getSetting("Service Name"));
GlobalVariables.setServicedesc(_configstream.getSetting("Service Description"));
ServiceName = _configstream.getSetting("Service Name");
//setting logger level
logger.setLogLevel(0);
logger.info("System Event", "Starting service");
processThread = new Thread(ProcessManager);
processThread.Start();
}
private ServiceController controller = new ServiceController(_configstream.getSetting("Service
Name"));
...
}
public class ConfigStream
{
// set properties of ConfigStream
public string config { get; private set; }
// constructor with config as an argument
public ConfigStream(string config_location)
{
string config = config_location;
}
// constructor with no arguments
public ConfigStream()
{
config = GlobalVariables.cwd + "\\" + GlobalVariables.configFileName;
}
...
}
当我实例化 Service 类的一个实例时 - 从 ServiceBase 类派生 - 在实例化过程中跳过我为 Service 类创建的构造函数
它不会被跳过。 这只是导致您出现问题的初始化顺序。
在运行任何构造函数的代码之前,首先初始化成员字段。 因此,当调用controller
的初始化程序时,会抛出异常,因为_configStream
为空。 有关更多信息,请参阅此问答。
旁注:此外,将_configStream
字段声明为static
并同时在每次创建实例时从构造函数初始化它是一个非常糟糕的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.