Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created February 3, 2019 09:00
Show Gist options
  • Save danielplawgo/a5f2267d98656a99012e286e3e2d2321 to your computer and use it in GitHub Desktop.
Save danielplawgo/a5f2267d98656a99012e286e3e2d2321 to your computer and use it in GitHub Desktop.
Topshelf - tworzenie usługi systemowej
public class Downloader : IDownloader
{
public void Download(string url)
{
var client = new WebClient();
var content = client.DownloadString(url);
}
}
public interface IDownloader
{
void Download(string url);
}
public class DownloadViewModel
{
[Required]
public string Url { get; set; }
}
public class HangfireService
{
private BackgroundJobServer _server;
static HangfireService()
{
GlobalConfiguration.Configuration
.UseSqlServerStorage(@"Server=localhost\sqlexpress;Database=TopshelfExample;Trusted_Connection=True;");
}
public void Start()
{
var options = new BackgroundJobServerOptions();
_server = new BackgroundJobServer(options);
}
public void Stop()
{
if(_server != null)
{
_server.Dispose();
}
}
}
public class HomeController : Controller
{
private Downloader _downloader = new Downloader();
public ActionResult Index()
{
return View();
}
public ActionResult Download()
{
return View(new DownloadViewModel());
}
[HttpPost]
public ActionResult Download(DownloadViewModel viewModel)
{
if(ModelState.IsValid == false)
{
return View(viewModel);
}
BackgroundJob.Enqueue(() => _downloader.Download(viewModel.Url));
return RedirectToAction("Download");
}
}
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.UseNLog();
x.Service<HangfireService>(h =>
{
h.ConstructUsing(n => new HangfireService());
h.WhenStarted(s => s.Start());
h.WhenStopped(s => s.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Hangfire Service");
x.SetDisplayName("Hangfire Service");
x.SetServiceName("Hangfire Service");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment