I have been working on converting my tightly coupled method into one that can be unit tested and have sought some advice on here. I now have my method passing its unit test thanks to some advice - however I now find that I cant call the method from my application. I used to access my GetAllProductsFromCSV() method from the controller with the following:
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);
}
The Method was as follows:
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;
}
}
I have now made the following changes in the ProductCSV class:
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;
}
Along with the following class & 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);
}
As I said, the Unit-Test on method GetAllProductsFromCSV completes successfully now however when I try accessing the method from my controller I get a NullReferenceException on the reader.ReadAllLines call within GetAllProductsFromCSV. It makes sense to me that when I attempt to create an instance of ProductsCSV from within the controller - I am not passing in any parameters... The constructor for the class however requests a IProductsCsvReader. What I cant figure out is how do I actually make the call to the method now? I hope that is clear??
First lets update ProductsCSV to have a backing interface
public interface IProductsCSV {
List<ProductItem> GetAllProductsFromCSV();
}
public class ProductsCSV : IProductsCSV {
//...other code removed for brevity
}
The controller wound now depend on the abstraction introduced above, decoupling it from the concrete implementation from the original controller. Though a simplified example, this allows the controller to be easier to maintain and unit-test in isolation.
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);
}
}
Note how the action matched exactly what you had before except for how the products is created.
Finally now that the controller has been refactored for dependency inversion, the framework needs to be configured to be able to inject the dependencies into the the controller when requested.
You can eventually use your library of choice but for this example I am using what they used in documentation
ASP.NET MVC 4 Dependency Injection
Never mind the version. The implementation is transferable.
In the documentation above they used Unity for their IoC container. There are many container libraries available so search for the one you prefer and use that.
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);
}
}
}
You would call the above bootstrapper in your start up code.
For example
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();
}
So now when ever the framework has to create the ProductsController it will know how to initialize and inject the controller's dependencies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With