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:
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.
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;
public ProductRepository()
{
}
public ProductRepository(IApplicationEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
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:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
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"];
});
services.AddMvc();
services.AddSingleton<ProductRepository>();
}
I have just added:
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:
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.
From the filepath, I extracted the file contents which are JSON data.
Also I have also displayed the products in the view. For this purpose, I have added a model class as below:
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:
Points of Interest
- ASP.NET 5
- Dependency Injection
History