Dependency Injection:
First, you have to correctly grasp the concept of 'Dependency Injection':
public TownController()
{
_townService = new TownService(this.ModelState, null);
}
TownController
isn't getting any dependency injected to it, and you're instantiating _townService
using a hard-coded TownService
implementation.
It should look more like this:
private ITownService _townService;
public TownController(ITownService townService)
{
_townService = townService;
}
As you can see, ITownService
implementation is being injected into the controller (using its constructor).
Now, if your injected dependency (ITownService
) has its own dependencies (IUnitOfWork
), it doesn't mean that your controller has to get injected all those dependencies as well, because when ITownService
is injected to the controller, it is already initialized and its dependencies have already been injected to it.
Most people use Dependency Injection Frameworks to achieve all that (and much more), here's a simple Unity example for ASP.NET MVC:
// some code omitted for brevity
internal static class DependencyResolvingConfig
{
internal static IUnityContainer Configure()
{
var container = new UnityContainer();
RegisterTypes(container);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
internal static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<ITownService, TownService>();
}
}
This line:
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Is telling ASP.Net MVC that whenever it instantiating a new controller with dependency, it will ask UnityDependencyResolver
to provide the implementation, Unity will then do that according to the configuration above.
ModelStateDictionary:
Another problem is that your service layer is using ModelStateDictionary
:
The concept of a ModelState
is (generally) the presentation-layer concern and is used for validation and getting/setting errors back/from the UI (traditionally HTML forms).
You should check and validate the Model State in your controllers, and then (usually only if it's valid) you call the service layer to perform the actual action.
Also, you'd have to add a reference to System.Web.Mvc
Assembly solely for the purpose of ModelState
usage (which is not recommended).