.NET Core 创建Windows服务
.NET Core 创建Windows服务
写在前面
使用 TopShelf+Autofac+AutoMapper+Quartz+NLog 完成现有项目定时调度任务
1.相关NetGet包
- 依赖注入 Alexinea.Autofac.Extensions.DependencyInjection
- 对象映射 AutoMapper.Extensions.Microsoft.DependencyInjection
- 调度 Autofac.Extras.Quartz
- Topshelf注入 Topshelf.Autofac
- Topshelf日志 Topshelf.NLog/Topshelf.Log4Net
2.添加Autofac自动映射服务
- 引入 Alexinea.Autofac.Extensions.DependencyInjection
3.添加AutoMapper自动映射类
- 引入 AutoMapper.Extensions.Microsoft.DependencyInjection
- 添加测试类 User、UserDto
- 添加服务类 IUserRepository、UserRepository、IUserService、UserService,获取配置文件中的User信息并转换为业务模型UserDto
- 添加映射配置文件 MapperProfiles
- 添加Autofac扩展 AutoMapperExtensions
public static class AutoMapperExtensions
{
public static ContainerBuilder ConfigureAutoMapper(this ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.AsClosedTypesOf(typeof(ITypeConverter<,>))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(AutoMapperExtensions).Assembly)
.AssignableTo<Profile>().As<Profile>();
builder.Register(c => {
var profiles = c.Resolve<IEnumerable<Profile>>();
var context = c.Resolve<IComponentContext>();
return new MapperConfiguration(x => {
foreach (var profile in profiles) x.AddProfile(profile);
x.ConstructServicesUsing(context.Resolve);
});
}).SingleInstance().AsSelf();
builder.Register(c => {
var context = c.Resolve<IComponentContext>();
var config = context.Resolve<MapperConfiguration>();
return config.CreateMapper();
}).As<IMapper>();
return builder;
}
}
- 添加自定义服务扩展 ServicesExtensions
public static class ServicesExtensions
{
public static ContainerBuilder ConfigureSelf(this ContainerBuilder builder)
{
var services = new ServiceCollection();
// register appsettings.json
services.Configure<User>("UserConfig", Settings.Instance.Configuration.GetSection("User"));
builder.Populate(services);
// register services repositories
builder.RegisterAssemblyTypes(typeof(UserRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(UserService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
return builder;
}
}
4.添加Quartz调度任务
- 引入 Autofac.Extras.Quartz
- 添加调度任务类 MyJob1
- 添加Autofac扩展 QuartzExtensions
public static ContainerBuilder ConfigureQuartz(this ContainerBuilder builder)
{
// 1) Register IScheduler
builder.RegisterModule(new QuartzAutofacFactoryModule());
// 2) Register jobs
builder.RegisterModule(new QuartzAutofacJobsModule(typeof(MyJob1).Assembly));
return builder;
}
5.添加日志
- 引入 NLog.Extensions.Logging
6.创建TopShelf服务
- 引入 Topshelf.NLog
- 引入 Topshelf.Autofac
7.发布并添加Windows服务
- 发布为独立文件
- 添加安装(install.bat)和卸载文件(uninstall.bat)
cd /d %~dp0
Sample.Topshelf.exe install
pause
cd /d %~dp0
Sample.Topshelf.exe uninstall
pause