且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有DbContext的服务器端计时器

更新时间:2023-11-27 21:52:34

最后我在多次测试后发现了问题,我需要参加
asp.net拥有的Strong Debedenty注入的优势,并将该类添加为服务,我也使用 IHostedService 作为我的服务类的接口,这是该服务的一个示例FinalTest(重命名为FinalTest的警报)

finally I have found the problem after many test, I needed to take advantage of the Strong Debedenty injection that asp.net have, and add the class as service, also I used IHostedService as interface for my service class, here is an example of the service FinalTest (renamed Alarm to FinalTest)

internal class FinalTest : IHostedService, IDisposable
{

    private Timer aTimer;
    public static List<Grocery> List;
    private AppDbContext db;
    // variable  to test that timer really works
    public static int test2;


    public FinalTest( AppDbContext _db )
    {
        db = _db;

    }

    //This method runs at the start of the application once only as FinalTest was set as Singleton in services
    public Task StartAsync(CancellationToken cancellationToken)
    {
        test2 = 1;
        aTimer =new Timer(CheckDBEvents, null , TimeSpan.Zero , TimeSpan.FromSeconds(10) );
        return Task.CompletedTask;
    }

    //Method runs every TimeSpan.FromSeconds(10)
    private void CheckDBEvents(object state)
    {

        var users = from u in db.Grocery where u.basic == true select u;
        List = users.ToList();
        //increase test2 To see changes in the real world
        test2++;
    }


    //--------shutdown operations---------//
    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        aTimer?.Dispose();
    }


}

现在,如果我将其注入服务 services.AddSingleton(FinalTest)中,因为我会得到范围异常,因为在SingleTon服务中使用作为范围服务的AppDbContext不好,不能有效地推广AppDbContext对于Singleton来说,这将来会引起问题,所以我不得不为AppDbContext创建另一个构造函数

Now if i injected this in the service services.AddSingleton(FinalTest) as it is I would get an scoped exceptions because using AppDbContext which is Scoped service in SingleTon service is not good and effectively promote AppDbContext To Singleton which is gonna cause problems in the future So I had to Create another constructor for AppDbContext

    public class AppDbContext : DbContext
{
    //Scoped constructor
    public AppDbContext(DbContextOptions<AppDbContext>  options) : base(options)
    {

    }

    //Singletone constructor
    public AppDbContext(DbContextOptions<AppDbContext> options,string connection)
    {
        connectionString = connection;
    }
    private string connectionString;
    //this is an override to OnConfiguring that's 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        if (connectionString != null)
        {
            var config = connectionString;
            optionsBuilder.UseSqlServer(config);
        }

        base.OnConfiguring(optionsBuilder);
    }
    //DbSet

    public DbSet<Grocery> Grocery { get; set; }

}

最后将两个 AppDbContext相加 FinalTest 到服务

 var connection = @"Server=(localdb)\mssqllocaldb;Database=FridgeServer.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
 services.AddDbContext<AppDbContext>(
            options => {
                //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                options.UseSqlServer(connection);
                //var config = Configuration["Data:DefaultConnection:ConnectionString"];

                //options.UseInMemoryDatabase("Grocery")
            }
        );

  services.AddSingleton<IHostedService,FinalTest>(s => new FinalTest(new AppDbContext(null, connection) ));

现在这是我的经验,而这一切都是有趣的经历,阅读有关依赖注入,Ioc和
编程的其他概念和模式,如果有人遇到某些问题,或者甚至想了解更多有关asp.net的信息,这里有一些帮助,第一个是最重要的。

Now that's my experience and it was all in all a fun experience reading all about Dependency injection and Ioc and other concept and pattern of programing if anyone face some of those problem or even want to know more about asp.net, here are some that helped ,the first one is the most important

http://deviq.com/category/principles/
http://deviq.com/dependency-inversion-principle/
https://docs.microsoft。 com / en-us / aspnet / core / fundamentals / dependency-injection?view = aspnetcore-2.1
在ASP .Net Singleton中使用DbContext注入的类
https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in -microservices-with-hostedservice-and-the-backgroundservice-class-net-core-2-x /

感谢@KienChu告诉我IHostedService,希望对您有所帮助

thanks to @KienChu for telling me about IHostedService , I Hope this helps someone