separation of concerns in MVC
One of the important feature of the MVC it enables separation of concerns.
independent as possible
I want the components in my
applications to be as independent as possible and to have as few interdependencies as I can arrange
abstract interfaces
In an ideal situation, each component knows nothing about any other component and only deals with other areas of the
application through abstract interfaces. This is known as loose coupling, and it makes testing and modifying applications easier.
Example
A simple example will help put things in context. If I am writing a component called MyEmailSender that will send emails,
I would implement an interface that defines all of the public functions required to send an e-mail, which I would call IEmailSender.
Any other component of my application that needs to send an e-mail—let’s say a password reset helper called
PasswordResetHelper—can then send an e-mail by referring only to the methods in the interface. There is no direct
dependency between PasswordResetHelper and MyEmailSender.
By introducing IEmailSender, I ensure that there is no direct dependency between PasswordResetHelper and
MyEmailSender. I could replace MyEmailSender with another e-mail provider or even use a mock implementation
Problem: objects that implement interfaces
Interfaces help decouple components, but I still face a problem: C# doesn’t provide a built-in way to easily create objects that
implement interfaces, except to create an instance of the concrete component with the new keyword. I end up with code like
this:
public class PasswordResetHelper {
public void ResetPassword() {
IEmailSender mySender = new MyEmailSender() ;
//...call interface methods to configure e-mail details...
mySender.SendEmail();
}
made things worse
This undermines my goal of being able to replace MyEmailSender without having to change PasswordReset
helper and means that I am only part of the way to loosely coupled components. The PasswordResetHelper class is
configuring and sending e-mails through the IEmailSender interface, but to create an object that implements that interface,
it had to create an instance of MyEmailSender. In fact, I have made things worse for myself because
PasswordResetHelper now depends on the MyEmailSender class and the IEmailSender interface, as
By using interface you make the class depending on each other and that is against the separation of concerns in MVC.
solution
What I need is a way to get objects that implement an interface without having to create the object directly. The solution to thisproblem is called dependency injection (DI), also known as Inversion of Control (IoC).
DI is a design pattern that completes the loose coupling process. As I describe DI, you might wonder what the fuss is about,
but bear with me—this is an important concept that is central to effective MVC development and it can cause a lot of confusion.
No comments:
Post a Comment