0

I have a concern. I want to know how can we make use of in-memory class in c# .Net using MVC 4 in Visual Studio 2010. i mean to say i do not want to use database or any other external storage medium even repository.

I want to store Data, retrieve data from that class.

I heard about "Caching" but it have its own limitations.

I also not to use any type of repositories, because using repository, i have made already using http://www.edandersen.com/2013/05/30/asp-net-mvc-basics-part-2-viewmodel-to-model-mapping-and-editing/.

So can you suggest me how to do this?

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Mayank
  • 141
  • 1
  • 1
  • 12

2 Answers2

1

What's your goal?

If the data is important to persist you can't have it in memory. IIS apps can restart at any time due to many reasons. The data is then lost without notice.

If the data is meant as a cache either use indeed a cache or a static variable (with proper synchronization).

usr
  • 168,620
  • 35
  • 240
  • 369
  • 1
    This is a good answer (although OP never mentioned IIS). There's a discussion here about storing information for a game - which is one type of scenario where you might not use a database - although they recommend using a file for storage anyway: http://www.codeproject.com/Questions/486416/Howplustoplussaveplusdataplusinplusc-pluswithout. If you are coming from a WebForms background and want to use a ViewState type mechanism have a look at http://stackoverflow.com/questions/2230519/asp-net-c-sharp-mvc-how-do-i-live-without-viewstate – Aaron Newton Nov 02 '14 at 03:14
  • For a very high throughput game I'd probably store all data in memory because there's no way to do something else. That causes headaches at deployment or patch time. For a low throughput game I'd use a persistent data store so that none of these concerns come into play. – usr Nov 02 '14 at 08:55
1

You could use a static object instance. For example, let's say that you have a User class:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and then have a static container for your entities:

public static class Container
{
    static Container()
    {
        Users = new ConcurrentBag<User>();
    }

    public static IEnumerable<User> Users { get; set; }
    ...
}

And then you can access this static instance from anywhere in your code. Obviously since ASP.NET MVC is a multithreaded environment you will need to properly synchronize the access to those variables. For example using ConcurrentBag<User> instead of a List<User> implementation.

and then in your controller you could access your in-memory data store:

public ActionResult Index(int id)
{
    var user = Container.Users.FirstOrDefault(x => x.Id == id);
    if (user == null)
    {
        return HttpNotFound();
    }

    return View(user);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928