在下面的代码中,为了清晰起见,在第二类中使用 config 和 monitor 很简单。应该如何创建/注册/解决计时器?似乎它不能在第一类中完成,因为它需要第二类的构造函数参数值,但如果我理解正确,那么所有寄存器/解析都应该在第一类中进行。
using System;
using System.ServiceProcess;
using System.Threading;
using Autofac;
namespace MyServiceApp
{
static class MyServiceAppMain
{
static void Main()
{
using (var container = InitContainer())
{
container.Resolve<MyService>().Start();
}
}
private static IContainer InitContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Configuration>().As<IConfiguration>();
builder.RegisterType<ServicesMonitor>();
builder.RegisterType<MyService>();
IContainer container =
builder.Build(Autofac.Builder.ContainerBuildOptions.None);
return container;
}
}
public partial class MyService : ServiceBase, IMyService
{
private Timer _processTimer;
private int _intervalSize;
private IConfiguration _config;
private ServicesMonitor _monitor;
public MyService(IConfiguration config, ServicesMonitor monitor)
{
InitializeComponent();
_config = config;
_monitor = monitor;
_config.ReadAppConfig();
}
public void Start()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
_intervalSize = _config.IntervalMinutes * (60 * 1000);
_processTimer =
new Timer(ProcessTimer_Elapsed, null, Timeout.Infinite, _intervalSize);
}
private void ProcessTimer_Elapsed(object sender)
{
_processTimer.Change(Timeout.Infinite, _intervalSize);
}
}
}