如何将数据从控制器传递到后台服务 [英] How to pass data from a controller to a background service

本文介绍了如何将数据从控制器传递到后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的Web api项目,其中包含每秒执行一次方法的后台服务.此方法遍历列表,仅打印(暂时)一些统计信息.我在后台服务的构造函数中声明了一个新列表.

I'm trying to write a simple web api project with a background service executing a method every second. This method loops over a list and just prints out (for the moment) some statistics. I declared a new list in the constructor of the background service.

我目前在从控制器内部添加和删除项目时遇到一些问题.

I'm currently encountering some issues with adding and removing items from inside the controller.

public UsersController(IUserBackgroundService userService)
{
   private readonly IUserBackgroundService _userService;

   public UserController(IUserBackgroundService userService)
   {
       _userService = userservice;
   }

   [HttpPost]
   public IActionResult PostUser(User user)
   {
      _userService.Add(user) 
   }
}

public UserService: BackgroundService, IUserService
{
    private List<User> Users;

    public UserService()
    {
       Users = new List<Users>();
    }
    protected override ExecuteAsync(CancellationToken token)
    {
        //this will execute the GenerateUserStats every second
    }

    //this method is being executed every second 
    protected Task GenerateUserStatistics()
    {
        Console.WriteLine($"Nr. of users {users.count}");
        foreach(var user in users)
        {
            Console.WriteLine($"{user.fname} {user.sname}");
        }
    }

    //add a user to the collection
    // this is called by the PostUser method of my controller.
    public void AddUser(User user)
    {
        Users.Add(user);
    }

    public void RemoveUser(string id)
    {
        var user = Users.FirstOrDefault(u => u.Id == id);
        Users.Remove(user);
    }
}

我希望每次调用PostUser()时,Users列表都会增加,而我的GenerateStatistics()方法应打印出正确的值,而打印出来的只是Nr个用户0.

I'd expect that every time I call the PostUser() the Users list should increase and my GenerateStatistics() method should print out the correct values, instead all it prints out is Nr of users 0.

我将该服务注册为托管服务和单例.目前,我在代码中省略了一些内容,因为我在这台机器上没有代码.

I registered the service as a hostedservice and a singleton. I omitted some things from the code for the moment because I don't have the code on this machine.

推荐答案

将您的backgroundService注册为Startup.cs的 ConfigureServices 中的 IHostedService ,如下所示:

Register your backgroundService as the IHostedService in the ConfigureServices of Startup.cs like below :

 services.AddSingleton<UserService>();
 services.AddSingleton<IHostedService, UserService>(
            serviceProvider => serviceProvider.GetService<UserService>());

然后在控制器中添加依赖项注入服务:

Then dependency inject service in controller :

 public class UsersController : ControllerBase
{
    private readonly UserService _userService;

    public UsersController(UserService userService)
    {
        _userService = userService;
    }

    [HttpPost]
    public IActionResult PostUser(User user)
    {
        _userService.AddUser(user);
        return Ok();
    }
}

参考资料: https://github.com/simpleinjector/SimpleInjector/issues/596

这篇关于如何将数据从控制器传递到后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆