Question

Im developing a asp.net small website and thought about using 3-tier design pattern (Gui, BLL, DAL). My main problem is that i feel bit lost with how should i handle the caching right.

1.First, where should the caching be done? Is it in the GUI website or in the BLL? 2.Second, it feels too messy to me, any chance anyone could provide me a simple example of how caching is done in a good way with all 3 parts of the 3tier? 3.Last, do u find okay to use 3tier for my need?

Was it helpful?

Solution

Personally I really like 3-tier structure and I can only recommend it. Let's see a simple example with some minor caching. We focus on the structure now.

Let's suppose we have the following code-first structure.

public class BlogEntry
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
}
public class Category 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Blog> Blogs { get; set; }
}
public BlogContext : DbContext
{
    public DbSet<Category> Category { get; set; }
    public DbSet<BlogEntry> Entry { get; set; }
}

Mind that EF will create the primary and foreign keys in the DB by naming conventions (like "Id"). You can use Db-first model as well, not a problem.

Let's have some DTO objects (see MSDN or wiki) like:

public class CategoryDto
{
    // To use in LINQ .Selector() 
    public Expression<Func<Category, CategoryDto>> Selector = efCategory => new CategoryDto
    {
        Id = efCategory.Id,
        Name = efCategory.Name,
    }
    public int Id { get; set; }
    public int Name { get; set; }
}

Of course categories are not changing often, so we may create some sort of cache for them. The caching in this case is clearly in BLL-level, using Dto objects. Update: This is good only if you have some data that is very unlikely to change but accessed very frequently. Otherwise don't bother with it.

public class MainCache
{
    // Make it singleton
    // Create some init and a refresh method, watch for thread-safety
    public List<CategoryDto> Categories { get; set; } 
}

So the controller level can access the cache like this: Update: Now the result of the action itself is cached, see details here. This is a safe solution, the framework does everything.

[HttpGet]
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult DisplayCategories()
{
    // Calling BLL, receiving Dto objects
    var model = MainCache.Instance.Categories; 
    return View(model);
}

Hope, you get it. I think this is a general structure that can be used in various situations. If something is not clear just ask.

Update: Minor code fix, and about caching

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top