通过依赖注入在 MVC 6 中访问文件路径






4.89/5 (5投票s)
如何在应用程序中使用 DI 访问文件
引言
在 Visual Studio 中开发网站或 WPF 应用程序时,有时我们需要访问应用程序中的文件以进行读取或写入数据。 在使用 Visual Studio 2015 的 MVC 6 中,这可以通过依赖注入 (DI) 来实现。 在本技巧中,我将解释如何注入服务以访问文件路径。
背景
在 Visual Studio 中使用 Web 或 WPF 应用程序时,有时会创建文件并将其存储在工作项目的文件夹或项目的根目录中。 无论它在哪里,当应用程序或服务部署到生产环境时,如果需要,也必须提供访问这些文件的方法。 在使用 MVC 6 的 Visual Studio 2015 中,可以使用 IApplicationEnvironment
接口作为依赖项来访问应用程序中的文件或文件夹。 简而言之,我将解释如何在 MVC 6 应用程序中完成它。
ASP.NET 5 中的依赖注入 (DI)
依赖注入 (DI) 是一种流行的软件设计模式,在控制反转的情况下尤其有效,其中一个或多个依赖项被注入到依赖对象中。 该模式用于创建松耦合且可测试的程序设计。 在 ASP.NET 5 中,依赖注入 (DI) 是一等公民。 已经提供了一个最小的 DI 容器,但如果默认容器不能满足需求,则可以引入自定义容器。
要了解有关 ASP.NET 5/vNext 中的 DI 的更多信息,请查看 MSDN 博客:
描述
我所做的是创建了一个 JSON 文件,其中包含一些 static
产品信息,这些信息将通过存储库类访问以从中读取内容。 我创建了一个名为 data 的新文件夹,并将 JSON 文件放置在该文件夹中,并将其命名为 product.json。 文件内容如下:
然后,我创建了以下存储库类,该类访问该文件并返回整个路径作为 string
,以便我们可以从中提取文件。
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;
}
}
}
为了在我们的应用程序中使用 DI 注入器,我们需要在 Startup.cs 中的 ConfigureServices
方法中配置此存储库类,如下所示:
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();
}
我只是添加了
services.AddSingleton<ProductRepository>();
到 ConfigureServices
方法中的默认服务列表中。
之后,我调用了存储库方法以返回文件路径,如下所示:
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();
}
}
}
完成此操作后,当我使用 Debug 运行应用程序时,我获得了包含完整文件路径的以下文件。
从文件路径中,我提取了文件内容,这些内容是 JSON 数据。
我还将产品显示在视图中。 为此,我添加了一个模型类,如下所示:
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; }
}
完成所有这些操作后,输出如下所示:
关注点
- ASP.NET 5
- 依赖注入
历史
- 2015-02-06:已提交