Thursday, July 02, 2009

A circular dependency in Asp.Net mvc contact manager example

I wrote a post about my understanding of asp.net mvc contact manager example, this is a very good example to  demonstrate how to separate your code into different parts of application. Particularly, the example introduced a service layer IContactManagerService to wrapper the repository and validation logic.  The controller doesn’t talk to the repository layer directly, instead , the controller talks to service layer. All in fine unless you try to use some dependency injection framework such as NInject.

Here is the problem, the controller constructor takes IContactManagerService as a parameter.

    public class ContactController : Controller
{
private IContactManagerService _service;

public ContactController()
{
_service = new ContactManagerService(new ModelStateWrapper(this.ModelState));
}

public ContactController(IContactManagerService service)
{
_service = service;
}

}




The ContactManagerService needs take IValidationDictionary as a parameter, however, the implementation of IValidationDictionary ModelStateWrapper needs to take a ModelStateDictionary, and this ModelStateDictionary needs to be the ModalState object of the controller, so it introduces a dependency on the controller.



    
public class ModelStateWrapper : IValidationDictionary
{
private ModelStateDictionary _modelState;

public ModelStateWrapper(ModelStateDictionary modelState)
{
_modelState = modelState;
}

public void AddError(string key, string errorMessage)
{
_modelState.AddModelError(key, errorMessage);
}

public bool IsValid
{
get { return _modelState.IsValid; }
}
}


Everything is fine until you try to use an injection framework to create the controller, then it will complains the circular dependency.

0 comments: