I got some problems with HostedService / background classes in my ASP.NET MVC project.
What I need is a timer that process some functions every X seconds and when those functions reach goals, go to stop and repeat process.
I have implemented the service in StartUp file as below :
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<INetLogger, Log4NetLogger>();
services.AddSingleton<IConfigurationSetting, ConfigurationSetting>();
services.AddSingleton<BackgroundService, StrategyLoops>();
services.AddSingleton<IStrategyManager, StrategyManager>();
services.AddSingleton<IUnitOfWork, UnitOfWork>();
}
I have created the class that contains the inheritance and I have the builder for a UnitOfWork.
In this class I got the ExectuteAsync function that should contain the logic of program.
public class StrategyLoops : BackgroundService
{
private readonly IUnitOfWork Uow;
public StrategyLoops(IUnitOfWork uow)
{
Uow = uow;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Do logic stuff
await Task.Delay(2000, stoppingToken);
}
}
}
Now, what's my problem ?
When I start the program, nothing happens. I put some debug breakpoints, but the compiler don't pass through code and the logic doesn't start.
This logic calls server's API and there is running while loop, if I don't have a timer, the server kick me out for overload requests.
The project was little different at start, I got a "StrategyManager" class that implements different logic
services.AddSingleton<IStrategyManager, StrategyManager>();
For probing logic, I was calling the methods directly from HomeController, but now I don't know how to start ...
Notice that I'm a noob of OOP ...
StrategyManager:
public class StrategyManager : IStrategyManager
{
public bool IsDivisible(decimal x, decimal n){}
public decimal SpotTradeWallet(){}
private const int indexValore = 0;
private const int indexQuantity = 1;
private const string SELL = "sell";
private const string BUY = "buy";
public void Strategia1(IUnitOfWork uow, String symbol, decimal startValue, decimal
startQuantity){}
public void Strategia2(IUnitOfWork uow, string POBsymbol, string SOsymbol, string
HTsymbol, string SBsymbol, string Ssymbol){}
}
The other problem, my knowledge problem, is that I don't understand if I can implement the Background service also in the StrategyManager class, so I can call it more easily from a view.
Lots of thanks to anyone who will answer me
services.AddHostedService<StrategyLoops>();to ConfigureServices method?