public class LogServiceModule : Autofac.Module
{
public const string StateKey = "LogServiceModule";
protected override void Load(ContainerBuilder builder)
{
builder.RegisterBuildCallback(container =>
{
// Add Log
EventHandler evtExit = (sender, e) =>
{
// Update Log
};
AppDomain.CurrentDomain.ProcessExit += evtExit;
});
}
}
這寫法實際上記錄到的Log是服務 OnStart()、OnStop() 的Log
但如果想要紀錄服務裡面 Timer 每次執行和結束的時間
請問有辦法在注入時就寫好嗎? 感謝大家指教
如果想要紀錄服務裡面 Timer 每次執行和結束的時間
public class MyService
{
private readonly Timer _timer;
private readonly ILogger _logger;
public MyService(Timer timer, ILogger logger)
{
_timer = timer;
_logger = logger;
}
public void Start()
{
_timer.Elapsed += OnTimerElapsed;
_timer.Start();
}
public void Stop()
{
_timer.Elapsed -= OnTimerElapsed;
_timer.Stop();
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
_logger.LogInformation("Timer elapsed at {0}", e.SignalTime);
// ...
}
}
有辦法在注入時就寫好嗎?
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<LoggerFactory>().As<ILoggerFactory>();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>));
builder.RegisterType<Timer>().As<Timer>();
builder.RegisterType<MyService>().As<IMyService>();
}