Thoughts from the Wet Coast

The musings of an ASP.NET Developer from Canada's We(s)t Coast

Comments

Articles

 
     

Naif.Blog: 1. In ASP.NET Core Everything is Injected

Category: ASP.NET Core
Apr 12 2016

In my continuing project to build my own Blog Application using the new ASP.NET Core, I previously set the stage by reviewing the development environment, I will be starting with.  In this post I move on to displaying a simple list of Blogs.

Lets first take a look at what I will be building in this step.

image

The above image shows the display of two posts, each post has a title and an excerpt (or abstract).  This is the classic list view that most blog applications render when no specific post is selected.  While it is quite easy to build, it will introduce what I consider one of the most important features of the new ASP.NET Core platform – Dependency Injection is built in, so there is no excuse not to use this Best Practice.

We will be adding 2 new classes and one new interface to our project.  The first class we will be adding is our Post model class.

public class Post
{
    public string ID { get; set; }

    public string Title { get; set; }

    public string Author { get; set; }

    public string Slug { get; set; }

    public string Excerpt { get; set; }

    public string Content { get; set; }

    public DateTime PubDate { get; set; }

    public DateTime LastModified { get; set; }

    public bool IsPublished { get; set; }
}

This is the same model as MiniBlog and BlogEngine.Net uses as I am going to use the same XML format for Naif.Blog as those two applications.  Next we will need to add a Repository to manage the underlying Data Store.

public interface IBlogRepository
{
    IEnumerable GetAll();
}

For the Blog List View we only need the one method on our Repository – GetAll(). 

Everything is Injected

We will use this repository in our BlogController to fetch a list of blogs and provide them to the View.

public class BlogController : Controller
{
    private IBlogRepository _blogRepository;

    public BlogController(IBlogRepository blogRepository)
    {
        _blogRepository = blogRepository;
    }

    public IActionResult Index()
    {
        return View(_blogRepository.GetAll());
    }
}

We add the repository interface to our constructor as a parameter.  ASP.NET’s Dependency Resolver then automatically resolves this dependency at runtime.  We just need to register the actual implementation in our StartUp class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<iblogrepository,>();

    services.AddMvc();
}</iblogrepository,>

This brings us to our second additional class -  XmlBlogRepository.  Lets take a look at the constructor of this class.

public XmlBlogRepository(IHostingEnvironment env,
                                    IMemoryCache memoryCache,
                                    ILoggerFactory loggerFactory)
{
    _memoryCache = memoryCache;
    _logger = loggerFactory.CreateLogger();
    _postsFolder = env.WebRootPath + "/posts/";
}

Here we notice that we have three interfaces that are passed as parameters.  When ASP.NET’s Dependecy Resolver resolves the dependency in the BlogController it needs to construct an instance of XmlBlogRepository and so it in turn resolves these three dependencies – “In ASP.NET Core everything is injected”.

But where do these 3 dependencies come from.  Two of these dependencies are registered by the ASP.NET Core runtime – the IHostingEnvironment and the ILoggerFactory, and the IMemoryCache is injected by calling the AddCaching extension method of the IServiceCollection in StartUp.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCaching();
    services.AddTransient<iblogrepository,>();

    services.AddMvc();
}</iblogrepository,>

Most of ASP.NET Core’s major “components” support Dependency Injection.  This makes it super easy to follow this Best Practice.  All you have to do is to ensure all your dependencies are registered in ConfigureServices.

Fetching the Posts

Now that I have set up all of the dependencies I will turn my attention to retrieving the posts. 

Loading all the posts from the file system on every request is not very efficient, so I am using the built in Memory Caching to store the posts in ASP.NET Core’s default cache.  We could of course use any cache provider which has been written for ASP.NET Core such as the Azure Redis Cache – and because we are using the abstract interface in our XmlBlogRepository class it should just be a case of changing the code in ConfigureServices to enable the Redis cache instead of the built-in Memory Cache.

The GetAll method shows how we use the IMemoryCache interface.

public IEnumerable GetAll()
{
    IEnumerable posts;

    if (!_memoryCache.TryGetValue(_postsCacheKey, out posts))
    {
        // fetch the value from the source
        posts = GetPosts();

        // store in the cache
        _memoryCache.Set(_postsCacheKey,
            posts,
            new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(2)));
        _logger.LogInformation($"{_postsCacheKey} updated from source.");
    }
    else
    {
        _logger.LogInformation($"{_postsCacheKey} retrieved from cache.");
    }

    return posts;
}

The private method GetPosts is called whenever there is no posts collection in the cache. This code is similar to the code used in MiniBlog so I leave it to you, the reader, to check the source if you would like to see how to enumerate the xml files and parse them into a collection of Post objects.

Listing the Posts

And finally, now that we have retrieved the posts we can display them in our default View – Index.cshtml.

@using Naif.Blog.Models;

@model IEnumerable

@{
    foreach (var post in Model)
    {
        

@post.Title

@post.Excerpt

} }

That’s it – as you can see, once you let ASP.NET Core handle all your dependencies it it is quite simple to set up your application with a nicely decoupled architecture. As we flesh out the Naif.Blog application I will introduce other features of the new ASP.NET Core framework.

Source

The source for Naif.Blog can be found at https://github.com/cnurse/Naif.Blog.  If you want to find the state of the repository used in this post then you can find that at the tagged release v0.0.1 (https://github.com/cnurse/Naif.Blog/releases/tag/v0.0.1)

Categories

Tags