Dependency Injection With Unity in MVC 5 without repository and unit of work

Posted on

Problem

I want to use dependency injection with Unity in my application. I am not following repository pattern and unit-of-work (and don’t want to). I also have ViewModel in my controller action method. Please review my code and add your comments.

public class ProductCatagoryController : Controller
{
    private dataBaseContext _context;

    public ProductCatagoryController(IdataBaseContext context)
    {
        this._context = context as dataBaseContext;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult addNewCategory([Bind(Include = "catName,desc")]RegisterNewCatagoryViewModel RegisterNewCatagoryViewModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
                Mapper.CreateMap<RegisterNewCatagoryViewModel, Category>();
                Category category = Mapper.Map<Category>(RegisterNewCatagoryViewModel);
                category.catID = Guid.NewGuid().ToString();
                category.date_from = DateTime.Now;
                category.active = true;
                _context.Categories.Add(category);
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                loggerElmah.logElmah(e, "Adding New Category Failed");
            }
        }
        return View();
    }

    [HttpGet]
    public ActionResult addNewCategory()
    {
        return View();
    }

    // GET: ProductCatagory
    public ActionResult Index()
    {
        return View();
    }
}

In addNewCategory I am passing an object of a concrete class object, but I want to pass an interface of the viewmodel and bind it with actual implementation in the run-time through unity. How can I do this?

Also, can someone guide me on writing unit-tests for the above code?

Solution

Naming

  • Based on the naming guidelines methods should be named using PascalCasing casing.
    addNewCategory -> AddNewCategory

  • Based on the same guideline classes should be named using PascalCasing casing.
    dataBaseContext -> DataBaseContext and therefor IdataBaseContext -> IDataBaseContext

General

You are injecting an interface in the constructor, but then you cast it to the concrete implementation. If you don’t need any methods/properties of the concrete implementation, you should stick to the interface.

private IDataBaseContext _context;

public ProductCatagoryController(IDataBaseContext context)
{
    this._context = context;
}

This will make the ProductCatagoryController class independent of the concrete DatabaseContext object.

For the case that ModelState.IsValid is false, how will the consumer of this method see, that no category is added ?
If an exception occurs, the consumer of this method will only see it, if the log file is parsed. Returning an Exception view would do better.

Leave a Reply

Your email address will not be published. Required fields are marked *