简体   繁体   中英

Why isn't the in-memory repository reset in different requests when the service is registered as transient?

I am attempting to understand the meaning of AddTransient method. I created an asp.net webapi, the complete project can be seen here .

Let me quote the main code here:

public class StudentService : IStudentService
{
    private static List<Student> students = new List<Student>
    {
        new Student{Id=1,Name="Andy"},
        new Student{Id=2,Name="Bobby"}
    };


    public List<Student> Create(Student student)
    {
        students.Add(student);
        return students;
    }

    public List<Student> GetAll()
    {
        return students;
    }
}

and

[ApiController]
[Route("[controller]")]
public class StudentController : ControllerBase
{
    private readonly IStudentService iss;

    public StudentController(IStudentService iss)
    {
        this.iss = iss;
    }
    [HttpGet]
    public ActionResult<List<Student>> GetAll()
    {
        return Ok(iss.GetAll());
    }

    [HttpPost]
    public ActionResult<List<Student>> Create(Student student)
    {
        iss.Create(student);
        return Ok(iss.GetAll());
    }
}

In my understanding, because the service is registered as transient, every request should reset the students field to a list of 2 Student . In other words, every creation of new Student by sending POST request, the server should response with a list of only 3 Student .

But it turns out, the number of Student in the response becomes larger and larger if I do multiple creation.

Question

Why isn't the in-memory repository reset in different requests when the service is registered as transient?

Because the students field is static.

Yes, transient service class is instantiated each time, but in your case, every instance uses the same stafic field.

Just remove fhe static modifier and it will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM