Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML
Tip/Trick

Accessing FilePath in MVC 6 via Dependency Injection

Rate me:
Please Sign up or sign in to vote.
4.89/5 (5 votes)
1 Jun 2015CPOL2 min read 25.7K   83   5   4
How to access files within the application using DI

Introduction

While developing Web Site or WPF applications in Visual Studio, sometimes we need to access files within our applications for reading or writing data. In MVC 6 with Visual Studio 2015, this can be achieved via Dependency Injection(DI). In this tip, I will explain how can we inject the service for accessing the filepath.

Background

Working with Web or WPF applicaitons in Visual Studio, sometimes, files are created and stored in the working projects within a folder or root of the project. Wherever it is, the files when the application or service is deployed to production environment, then it is also necessary to provide the way for accessing the files if needed. In Visual Studio 2015 with MVC 6, it is feasible to use the IApplicationEnvironment interface as dependency for accessing files or folders within the application. Briefly, I will explain how it can be done within an MVC 6 application.

Dependency Injection (DI) in ASP.NET 5

Dependency Injection (DI) is a popular software design pattern particularly efficient in the case of Inversion of Control, in which one or more dependencies are injected into dependent objects. The pattern is used to create program designs that are loosely coupled and testable. In ASP.NET 5 dependency injection (DI) is a first class citizen. A minimalistic DI container has been provided out of the box but there are scopes to bring out custom containers if the default one does not serve the purposes.

To know more about DI in ASP.NET 5/vNext, please have a look the MSDN blog at:

Description

What I have done is created a JSON file containing some static product information that will be accessed via a repository class to read the contents from it. I have created a new folder called data and within this folder I have placed the JSON file and named as product.json. The contents of the file are as below:

Image 1

I have then created the following repository class that access the file and return the whole path as string so that we can extract the file from it.

C#
using Microsoft.Framework.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ApplicationFilePath.Models
{
    public class ProductRepository
    {
        private readonly IApplicationEnvironment _appEnvironment;
        //constructor
        public  ProductRepository()
        {

        }
        //injecting the interface
        public ProductRepository(IApplicationEnvironment appEnvironment)
        {
            _appEnvironment = appEnvironment;
        }

        //return the file path
        public string GetProduct()
        {
            var filepath = _appEnvironment.ApplicationBasePath + "\\data\\product.json";

            return filepath;
        }
    }
}

To use the DI injector within our application, we need to configure this repository class to Startup.cs within ConfigureServices method as below:

C#
public void ConfigureServices(IServiceCollection services)
     {
         // Add Application settings to the services container.
         services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

         // Add EF services to the services container.
         services.AddEntityFramework()
             .AddSqlServer()
             .AddDbContext<ApplicationDbContext>(options =>
                 options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
             // Add Identity services to the services container.
         services.AddIdentity<ApplicationUser, IdentityRole>()
             .AddEntityFrameworkStores<ApplicationDbContext>()
             .AddDefaultTokenProviders();

         // Configure the options for the authentication middleware.
         services.Configure<FacebookAuthenticationOptions>(options =>
         {
             options.AppId = Configuration["Authentication:Facebook:AppId"];
             options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
         });

         services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
         {
             options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
             options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
         });

         // Add MVC services to the services container.
         services.AddMvc();

         //add the singleton for the product repository
         services.AddSingleton<ProductRepository>();

         // Uncomment the following line to add Web API services
         // which makes it easier to port Web API 2 controllers.
         // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim
         // package to the 'dependencies' section of project.json.
         // services.AddWebApiConventions();
     }

I have just added:

C#
services.AddSingleton<ProductRepository>();

to the default list of services in the ConfigureServices method.

After that, I have called the repository method to return the filepath as below:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using ApplicationFilePath.Models;
using Newtonsoft.Json;

namespace ApplicationFilePath.Controllers
{
    public class HomeController : Controller
    {
        ProductRepository _productRepo;

        public HomeController(ProductRepository productRepo)
        {
            _productRepo = productRepo;
        }

        public IActionResult Index()
        {
            var product = _productRepo.GetProduct();

            var file= System.IO.File.ReadAllText(product);
            var products = JsonConvert.DeserializeObject<List<Product>>(file);

            return View();
        }
    }
}

After having done this, when I have run the application with Debug, I got the following file with full filepath.

Image 2

From the filepath, I extracted the file contents which are JSON data.

Image 3

Also I have also displayed the products in the view. For this purpose, I have added a model class as below:

C#
public class Product
   {
       [Key]
       public int Id { get; set; }
       public string ProductCode { get; set; }
       public string ProductName { get; set; }
       public string ProductType { get; set; }
       public decimal Price { get; set; }

       public List<Product> Products { get; set; }
   }

Having done all of these, the output shows as below:

Image 4

Points of Interest

  • ASP.NET 5
  • Dependency Injection

History

  • 02-06-2015: Submitted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Monster8414-Jun-15 2:43
Monster8414-Jun-15 2:43 
GeneralRe: My vote of 4 Pin
Mostafa Asaduzzaman4-Jun-15 8:25
Mostafa Asaduzzaman4-Jun-15 8:25 
Thanks
GeneralHelpful Tip Pin
Member 117071862-Jun-15 11:47
Member 117071862-Jun-15 11:47 
GeneralRe: Helpful Tip Pin
Mostafa Asaduzzaman2-Jun-15 11:49
Mostafa Asaduzzaman2-Jun-15 11:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.