I have an ASP.NET MVC web application. In the HomeController
, I want to create an array of objects of the class I need, so that when new objects are written to this array, it would not be overwritten, but added as new elements to itself.
For example: this is a piece of code from HomeController
. Here I create a static array of objects so that we can access it without creating a class object.
// ...
public static List<Person> personMessages { get; set; }
public HomeController()
{
personMessages = new List<Person>();
}
// ...
And this is the code from another class, in which I add new objects to this array ( personMessages
).
HomeController.personMessages.Add(personObj);
Console.WriteLine("Array count: " + HomeController.personMessages.Count);
When my application is running, after each addition of a new object, the length of the array will always be 1
and it will contain the last added object.
How to solve my problem and create something like a data repository (based on my array of objects personMessages
)?
This is really bad to have personMessages
as a member of the controller class. and you are accessing it using the controller class. It violates the single responsibility principle as well.
you should create a repository class and have a static member of it. you can create a method to add an item to the list.
public static class PersonRepository
{
public static List<Person> personMessages { get; set; } = new List<Person>();
public static void AddPerson(Person person)
{
personMessages.Add(person);
}
}
you can call the method like this PersonRepository.AddPerson(personObj)
;
As a suggestion, I think you should use some logging instead of Console.WriteLine
as it's not a console application.
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.