Is there a good/proper way of solving the dependency injection loop problem in the ASP.NET MVC ContactsManager tutorial?

As a general consideration, circular dependencies indicate a design flaw – I think I can safely say this since you are not the original author of the code 🙂

I wouldn’t consider an Initialize method a good solution. Unless you are dealing with an add-in scenario (which you aren’t), Method Injection is not the right solution. You have almost already figured that out, since you find it unsatisfactory that you need to manually invoke it because your DI Container can’t.

Unless I am entirely mistaken, the ContactController doesn’t need the IValidationDictionary instance before its Action methods are being invoked?

If this is true, the easiest solution would probably be to define an IValidationDictionaryFactory interface and make the ContactController constructor take an instance of this interface.

This interface could be defined like this:

public interface IValidationDictionaryFactory
{
    IValidationDictionary Create(Controller controller);
}

Any Action method on the controller that needs an IValidationDictionary instance can then invoke the Create method to get the instance.

The default implementation would look something like this:

public class DefaultValidationDictionaryFactory : IValidationDictionaryFactory
{
    public IValidationDictionary Create(Controller controller)
    {
        return controller.ModelState;
    }
}

Leave a Comment