gpt4 book ai didi

c# - 通过依赖注入(inject)执行我的类函数

转载 作者:行者123 更新时间:2023-11-30 14:47:19 25 4
gpt4 key购买 nike

我一直致力于将我的紧耦合方法转换为可以进行单元测试的方法,并在此寻求一些建议。由于一些建议,我现在让我的方法通过了单元测试 - 但是我现在发现我无法从我的应用程序调用该方法。我曾经使用以下方法从 Controller 访问我的 GetAllProductsFromCSV() 方法:

    public ActionResult Index()
{
var products = new ProductsCSV();
List<ProductItem> allProducts = products.GetAllProductsFromCSV();

foreach (var product in allProducts)
{
if (string.IsNullOrEmpty(product.ImagePath))
{
product.ImagePath = "blank.jpg";
}
}

return View(allProducts);
}

方法如下:

public class ProductsCSV
{
public List<ProductItem> GetAllProductsFromCSV()
{
var productFilePath = HttpContext.Current.Server.MapPath(@"~/CSV/products.csv");

String[] csvData = File.ReadAllLines(productFilePath);

List<ProductItem> result = new List<ProductItem>();

foreach (string csvrow in csvData)
{
var fields = csvrow.Split(',');
ProductItem prod = new ProductItem()
{
ID = Convert.ToInt32(fields[0]),
Description = fields[1],
Item = fields[2][0],
Price = Convert.ToDecimal(fields[3]),
ImagePath = fields[4],
Barcode = fields[5]
};
result.Add(prod);
}
return result;
}
}

我现在在 ProductCSV 类中进行了以下更改:

public class ProductsCSV
{
private readonly IProductsCsvReader reader;

public ProductsCSV(IProductsCsvReader reader = null)
{
this.reader = reader;
}

public List<ProductItem> GetAllProductsFromCSV()
{
var productFilePath = @"~/CSV/products.csv";
var csvData = reader.ReadAllLines(productFilePath);
var result = parseProducts(csvData);
return result;
}


private List<ProductItem> parseProducts(String[] csvData)
{
List<ProductItem> result = new List<ProductItem>();

foreach (string csvrow in csvData)
{
var fields = csvrow.Split(',');
ProductItem prod = new ProductItem()
{
ID = Convert.ToInt32(fields[0]),
Description = fields[1],
Item = fields[2][0],
Price = Convert.ToDecimal(fields[3]),
ImagePath = fields[4],
Barcode = fields[5]
};
result.Add(prod);
}
return result;
}

以及以下类和接口(interface):

public class DefaultProductsCsvReader : IProductsCsvReader
{
public string[] ReadAllLines(string virtualPath)
{
var productFilePath = HostingEnvironment.MapPath(virtualPath);
String[] csvData = File.ReadAllLines(productFilePath);
return csvData;
}
}

public interface IProductsCsvReader
{
string[] ReadAllLines(string virtualPath);
}

正如我所说,对方法 GetAllProductsFromCSV 的单元测试现在已成功完成,但是当我尝试从我的 Controller 访问该方法时,我在 reader.ReadAllLines 调用 GetAllProductsFromCSV 时收到 NullReferenceException。这对我来说很有意义,当我尝试从 Controller 中创建 ProductsCSV 的实例时 - 我没有传递任何参数......然而,该类的构造函数请求一个 IProductsCsvReader。我想不通的是我现在如何实际调用该方法?我希望这很清楚??

最佳答案

首先让我们更新 ProductsCSV 以获得支持界面

public interface IProductsCSV {
List<ProductItem> GetAllProductsFromCSV();
}

public class ProductsCSV : IProductsCSV {
//...other code removed for brevity
}

Controller 伤口现在依赖于上面介绍的抽象,将其与原始 Controller 的具体实现解耦。虽然是一个简化的示例,但这使 Controller 更易于维护和独立进行单元测试。

public class ProductsController : Controller {
private readonly IProductsCSV products;

public ProductsController(IProductsCSV products) {
this.products = products;
}

public ActionResult Index() {
List<ProductItem> allProducts = products.GetAllProductsFromCSV();
foreach (var product in allProducts) {
if (string.IsNullOrEmpty(product.ImagePath)) {
product.ImagePath = "blank.jpg";
}
}
return View(allProducts);
}
}

请注意除了 products 的创建方式外,操作与之前的操作完全匹配。

最后, Controller 已经针对依赖倒置进行了重构,框架需要配置为能够在请求时将依赖项注入(inject) Controller 。

你最终可以使用你选择的库,但对于这个例子,我使用的是他们在文档中使用的库

ASP.NET MVC 4 Dependency Injection

不要管版本。实现是可转移的。

在上面的文档中,他们使用 Unity 作为他们的 IoC 容器。有许多可用的容器库,因此请搜索您喜欢的并使用它。

public static class BootStrapper {

private static IUnityContainer BuildUnityContainer() {
var container = new UnityContainer();

//Register types with Unity
container.RegisterType<IProductsCSV , ProductsCSV>();
container.RegisterType<IProductsCsvReader, DefaultProductsCsvReader>();

return container;
}

public static void Initialise() {
//create container
var container = BuildUnityContainer();
//grab the current resolver
IDependencyResolver resolver = DependencyResolver.Current;
//create the new resolver that will be used to replace the current one
IDependencyResolver newResolver = new UnityDependencyResolver(container, resolver);
//assign the new resolver.
DependencyResolver.SetResolver(newResolver);
}
}

public class UnityDependencyResolver : IDependencyResolver {
private IUnityContainer container;
private IDependencyResolver resolver;

public UnityDependencyResolver(IUnityContainer container, IDependencyResolver resolver) {
this.container = container;
this.resolver = resolver;
}

public object GetService(Type serviceType) {
try {
return this.container.Resolve(serviceType);
} catch {
return this.resolver.GetService(serviceType);
}
}

public IEnumerable<object> GetServices(Type serviceType) {
try {
return this.container.ResolveAll(serviceType);
} catch {
return this.resolver.GetServices(serviceType);
}
}
}

您可以在启动代码中调用上述 Bootstrap 。

例如

protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

Bootstrapper.Initialise(); //<-- configure DI

AppConfig.Configure();
}

因此,现在每当框架必须创建 ProductsController 时,它就会知道如何初始化和注入(inject) Controller 的依赖项。

关于c# - 通过依赖注入(inject)执行我的类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45554330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com