我认为这更像是一种观点而不是事实,但我更喜欢在服务构建期间编写,然后使用 OnStart() 来激活我之前编写的服务。这是我通常的工作方式(使用 Topshelf)。例如:
程序.cs
public class Program
{
private static ILifetimeScope _scope;
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
public static void Main(string[] args)
{
try
{
XmlConfigurator.Configure();
// configure composition
_scope = CompositionRoot.CreateScope();
HostFactory.Run(x =>
{
x.UseLog4Net();
x.UseAutofacContainer(_scope);
x.Service<IMyService>(svc =>
{
svc.ConstructUsingAutofacContainer();
svc.WhenStarted(tc => tc.Start());
svc.WhenStopped(tc =>
{
tc.Stop();
_scope.Dispose();
});
});
x.RunAsNetworkService();
x.StartManually();
});
}
catch (Exception e)
{
Log.Error("An error occurred during service construction.", e);
throw;
}
}
}
作文.cs
internal class CompositionRoot
{
public static ILifetimeScope CreateScope()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyService>().As<IMyService>().SingleInstance();
// other things you want to register
return builder.Build();
}
}
imyservice.cs
public interface IMyService
{
void Start();
void Stop();
}
我在这里看到的唯一真正的缺点是,如果我使用像 Topshelf 这样的工具,我不能使用 DI 容器来获取我的 Service 类的实例
这是真的,但您不需要访问 program.cs 代码,只需访问 MyService 代码,它将代表您的服务的实际“核心”代码。
此外,当您停止服务时,您实际上会杀死它(除非您暂停它),因此无论您是否将其放在“onStart()”中,组合都会再次执行。
像往常一样,恕我直言。:)