We've taken over coding on a .NET MVC project, and as I'm relatively inexperienced with many of the MVC design approaches, I'm working on getting a good understanding of the design choices.
One aspect that's caught my attention is that each controller class is initialised using existing instances of services. In my non-MVC past, I usually kick off a service just when I need it, or at most have a service instance for that controller instance.
To show exactly what I mean:
public class AccountController : BaseController
private readonly IAccountService _iAccountService;
private readonly ISettingsService _iSettingService;
private readonly IGenericContentService _genericContentService;
private readonly IMemberService _memberService;
public AccountController(IAccountService iAccountService, ISettingsService iSettingService, IGenericContentService genericContentService, IMemberService memberService)
_iAccountService = iAccountService;
_iSettingService = iSettingService;
_genericContentService = genericContentService;
_memberService = memberService;
I think the below code is what's causing it to init the controllers with the required services:
public class MyApplicationRegistry : Registry
For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
My guess is that this improves performance, as you don't need a fresh instance of a service class each time you need it, or even for each controller.
But this design does make the code a bit more unwieldy. Changing a service method requires you to keep both the interface and the class synced, which just makes for a bit more "overhead" for each code change.
There's two other options I see:
- Create an instance for each service for each controller. I can see how this could become a problem for a heavily used application, but until then I don't see how it's an issue.
- Make the service methods all
staticso you don't need to create an instance of the class. To me it seems they pretty much are that already. So in my mind, this seems like a nice alternative. But I do suspect a general distaste for
staticmethods these days for reasons I'm still learning.
So how do these options compare? Am I missing something, and why does the above code pattern seem to be fairly popular for .NET MVC?
Looks like this is Dependency Injection
I did a bunch of more reading, and I see that this design is for dependency injection, and uses the StructureMap library. The merits of efficient, decoupled code are quite compelling, so it's seeming like the code I've shown is better than my two options, primarily from a design standpoint but also a performance standpoint.