What is the right granularity for dependencies while doing constructor or setter injection? - dependency-injection

I am trying to define some dependency injection guidelines for myself. What should be the right granularity while defining dependencies for a class that are to be injected either via constructor or setter injection? The class could be a service, repository, etc. Suppose there is a repository class, which looks like following:
public class ProductRepository
{
//Option-A
public ProductRepository(DataSource dataSource)
{
}
//Option-B
public ProductRepository(SqlSession sqlSession)
{
}
//Option-C
public ProductRepository(SqlSessionTemplate sqlSessionTemplate)
{
}
}
The minimum dependency required by the above class is DataSource interface. The repository class internally makes use of the SqlSessionTemplate (implementation of the SqlSession interface). As shown in the code, there are 3 choices for constructor for doing constructor injection. The following is my understanding:
Option-A (DataSource dependency)
This is the minimum dependency of the repository class. From consumer point of view this constructor is the right choice but it is not suitable from unit testing point of view because DataSource is internally consumed by the SqlSessionTemplate in the repository implementation.
Options-B (SqlSession dependency)
This is the right choice from unit testing point of view but not from the consumer point of view. Additionally the repository implementation is tightly coupled with specific implementation of the interface which is SqlSessionTemplate. Hence it will not work if the consumer passes some different SqlSession interface other than SqlSessionTemplate.
Options-C (SqlSessionTemplate dependency)
SqlSessionTemplate being an implementation and not an interface does not seem to be good for unit testing. Also, it is not good for the consumer as instantiating SqlSessionTemplate is more involved as compared to DataSource. Hence discarding this option.
Option-A and Option-B seems to be the available choices. But, there is a trade-off between consumer point of view and unit testing point of view and vice versa.
I am new to dependency injection. I seek advice from the DI experts. What is the right solution (if any)? What would you do in the above situation?
Thanks.

This is the minimum dependency of the repository class.
I think this is the starting point for figuring out the right amount of coupling. You should be injecting no more or less than is needed to fulfill the requirements.
That's a very general guideline, which is almost the equivalent of "it depends", but it's a good way to start thinking about it. I don't know enough about DataSource, SqlSession, or SqlSessionTemplate to answer in context.
The repository class internally makes use of the SqlSessionTemplate
(implementation of the SqlSession interface)
Why can't the repository simply use the interface as a dependency? Does the interface not cover all the public methods of the implementation? If it doesn't, is the interface even a useful abstraction?
I can't completely piece together what you are trying to do and how the dependencies work, but my best guess is either:
You need both SqlSession and DataSource injected via the constructor, or
You need SqlSession injected via the Repository's constructor, and DataSource injected into the SqlSessionTemplate's constructor

You are talking about unit testing your repository, but that would typically be rather useless because a repository is your gateway to the database and has a strong coupling with it. Unit testing should be done in isolation, but a repository can only be tested with the database. Thus: an integration test.
If you were able to abstract the database specific logic from the repository (as you seem to be doing) there would be nothing left to test, since the responsibility of the repository is to communicate with the database. And if there still IS a lot left to test, well... in that case your repository classes are probably violating the Single Responsibility Principle, which makes your repositories hard to maintain.
So since you would typically test a repository itself using a database, from a testing perspective it doesn't really matter what you inject, since you will have to construct an repository in such way that it will be able to connect to a database anyway.

Related

What is the best way to inject repositories into an ASP.NET controller

We have a project written in ASP.NET MVC and we use NInject to inject the repositories into the controllers. Currently we are using properties and the Inject-attribute to inject the repositories, which works well enough:
[Inject]
public IMyRepository MyRepos {get;set;}
An alternative way of injecting would be to do it "manually" using the NInjectServiceLocator:
var myRepos = NInjectServiceLocatorInstance.Resolve<IMyRepository>();
Now I was wondering about the following: the first method requires all repositories to be listed at the top (not necessarily at the top of course, but it's the most logical place) of a controller. Whenever a request is made, NInject instantiates each and every repository. This happens regardless of whether all of the repositories are actually needed inside a specific Action.
With the second method you can more precisely control which repositories are actually necessary and thus this might save some overhead when the controller is created. But you probably also have to include code to retrieve the same repository in multiple places.
So which one would be better? Is it better to just have a bunch of repository-properties or is it better to resolve the repositories which are actually necessary for a specific action when and where you need them? Is there a performance penalty involved for injecting "useless" repositories? Are there (even ;-) better solutions out there?
I prefer constructor injection:
private readonly IMyRepository _repository;
public MyController(IMyRepository repository)
{
_repository = repository;
}
All your dependencies are listed in one operation
Your controller does not need to know anything about NInject
You can unit-test your controller without NInjects involvment by stubbing interfaces straight to the constructor
Controller has a cleaner code
NInject or any other DI framework will do the work behind the scenes and leave you concentrating on the actual problem, not DI.
Constructor Injection should be your default choice when using DI.
You should ask yourself if the controller is really dependent on that specific class to work at all.
Maybe Method injection could also be a solution for specific scenario's, if you have only specific methods that needs dependencies.
I've never used Property Injection but Mark Seeman describes it in his book (Dependency Injection in .NET):
PROPERTY INJECTION should only be used when the class you’re developing has a good
LOCAL DEFAULT and you still want to enable callers to provide different implementations
of the class’s DEPENDENCY.
PROPERTY INJECTION is best used when the DEPENDENCY is optional.
NOTE There’s some controversy around the issue of whether PROPERTY INJECTION
indicates an optional DEPENDENCY. As a general API design principle, I
consider properties to be optional because you can easily forget to assign
them and the compiler doesn’t complain. If you accept this principle in the
general case, you must also accept it in the special case of DI. 4
A local default is described as:
A default implementation of an ABSTRACTION that’s defined in the same assembly as
the consumer.
Unless you're building an API I would suggest not to use Property Injection
Whenever a request is made, NInject instantiates each and every repository. This happens regardless of whether all of the repositories are actually needed inside a specific Action.
I don't think you should worry to much about the performance when using constructor injection
By far my favorite method is:
public class MyController : Controller
{
public IMyRepository MyRepos {get;set;}
public MyController(IMyRepository repo)
{
MyRepos = repo;
}
}
So you can use a NuGet package, such as Ninject.MVC3 (or MVC4) which has specific support for including the Ninject kernel inside the MVC's own IoC classes
https://github.com/ninject/ninject.web.mvc/wiki/MVC3
Once you have Ninject hooks in, you can let it do the work of injection instances into the controller's constructor, which I think is a lot cleaner.
EDIT:
Ahh, OK. Having read your question a bit more thoroughly, I see where you're going with this. In short, if you want to pick and choose which repo classes are instansiated then you will need to manually call, for example:
var myRepos = NInjectServiceLocatorInstance.Resolve<IMyRepository>();
You cannot configure Ninject (or any other IoC AFAIK) to selectively create object instances based on the currently execute method. That level of granularity is a real edge case I feel, which may be solvable by writing your own controller factory class, but that would be overkill.

Unit of Work with Dependency Injection

I'm building a relatively simple webapp in ASP.NET MVC 4, using Entity Framework to talk to MS SQL Server. There's lots of scope to expand the application in future, so I'm aiming for a pattern that maximises reusability and adaptability in the code, to save work later on. The idea is:
Unit of Work pattern, to save problems with the database by only committing changes at the end of each set of actions.
Generic repository using BaseRepository<T> because the repositories will be mostly the same; the odd exception can extend and add its additional methods.
Dependency injection to bind those repositories to the IRepository<T> that the controllers will be using, so that I can switch data storage methods and such with minimal fuss (not just for best practice; there is a real chance of this happening). I'm using Ninject for this.
I haven't really attempted something like this from scratch before, so I've been reading up and I think I've got myself muddled somewhere. So far, I have an interface IRepository<T> which is implemented by BaseRepository<T>, which contains an instance of the DataContext which is passed into its constructor. This interface has methods for Add, Update, Delete, and various types of Get (single by ID, single by predicate, group by predicate, all). The only repository that doesn't fit this interface (so far) is the Users repository, which adds User Login(string username, string password) to allow login (the implementation of which handles all the salting, hashing, checking etc).
From what I've read, I now need a UnitOfWork class that contains instances of all the repositories. This unit of work will expose the repositories, as well as a SaveChanges() method. When I want to manipulate data, I instantiate a unit of work, access the repositories on it (which are instantiated as needed), and then save. If anything fails, nothing changes in the database because it won't reach the single save at the end. This is all fine. My problem is that all the examples I can find seem to do one of two things:
Some pass a data context into the unit of work, from which they retrieve the various repositories. This negates the point of DI by having my Entity-Framework-specific DbContext (or a class inherited from it) in my unit of work.
Some call a Get method to request a repository, which is the service locator pattern, which is at least unpopular, if not an antipattern, and either way I'd like to avoid it here.
Do I need to create an interface for my data source and inject that into the unit of work as well? I can't find any documentation on this that's clear and/or complete enough to explain.
EDIT
I think I've been overcomplicating it; I'm now folding my repository and unit of work into one - my repository is entirely generic so this just gives me a handful of generic methods (Add, Remove, Update, and a few kinds of Get) plus a SaveChanges method. This gives me a worker class interface; I can then have a factory class that provides instances of it (also interfaced). If I also have this worker implement IDisposable then I can use it in a scoped block. So now my controllers can do something like this:
using (var worker = DataAccess.BeginTransaction())
{
Product item = worker.Get<Product>(p => p.ID == prodName);
//stuff...
worker.SaveChanges();
}
If something goes wrong before the SaveChanges(), then all changes are discarded when it exits the scope block and the worker is disposed. I can use dependency injection to provide concrete implementations to the DataAccess field, which is passed into the base controller constructor. Business logic is all in the controller and works with IQueryable objects, so I can switch out the DataAccess provider object for anything I like as long as it implements the IRepository interface; there's nothing specific to Entity Framework anywhere.
So, any thoughts on this implementation? Is this on the right track?
I prefer to have UnitOfWork or a UnitOfWorkFactory injected into the repositories, that way I need not bother it everytime a new reposiory is added. Responsibility of UnitOfWork would be to just manage the transaction.
Here is an example of what I mean.

Inversion of Control vs Dependency Injection

According to the paper written by Martin Fowler, inversion of control is the principle where the control flow of a program is inverted: instead of the programmer controlling the flow of a program, the external sources (framework, services, other components) take control of it. It's like we plug something into something else. He mentioned an example about EJB 2.0:
For example the Session Bean interface
defines ejbRemove, ejbPassivate
(stored to secondary storage), and
ejbActivate (restored from passive
state). You don't get to control when
these methods are called, just what
they do. The container calls us, we
don't call it.
This leads to the difference between framework and library:
Inversion of Control is a key part of
what makes a framework different to a
library. A library is essentially a
set of functions that you can call,
these days usually organized into
classes. Each call does some work and
returns control to the client.
I think, the point of view that DI is IOC, means the dependency of an object is inverted: instead of it controlling its own dependencies, life cycle... something else does it for you. But, as you told me about DI by hands, DI is not necessarily IOC. We can still have DI and no IOC.
However, in this paper (from the pococapsule, another IOC Framework for C/C++), it suggests that because of IOC and DI, the IOC containers and DI frameworks are far more superior to J2EE, since J2EE mixes the framework code into the components, thus not making it Plain Old Java/C++ Object (POJO/POCO).
Inversion of Control Containers other than the Dependency Injection pattern (Archive link)
Additional reading to understand what's the problem with old Component-Based Development Framework, which leads to the second paper above: Why and what of Inversion of Control (Archive link)
My Question: What exactly is IOC and DI? I am confused. Based on pococapsule, IOC is something more significant than just inversion of the control between objects or programmers and frameworks.
The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which "implements" and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller).
For example, rather than having the application call the implementations provided by a library (also known as toolkit), the library and/or framework calls the implementations provided by the application.
The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, where implementations are passed into an object through constructors/setters/service lookups, which the object will "depend" on in order to behave correctly.
Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using the general term "IoC" instead).
IoC without using DI, for example, would be the Template pattern because the implementation can only be changed through sub-classing.
DI frameworks are designed to make use of DI, and can define interfaces (or Annotations in Java) to make it easy to pass in the implementations.
IoC containers are DI frameworks that can work outside of the programming language. In some you can configure in metadata files (e.g. XML), the implementations to be used, which are less invasive. With some you can do IoC that would normally be impossible, like injecting an implementation at pointcuts.
See also this Martin Fowler's article.
In short, IoC is a much broader term that includes, but is not limited to, DI
The term Inversion of Control (IoC) originally meant any sort of programming style where an overall
framework or run-time controlled the program flow
Before DI had a name, people started to refer to frameworks that manage Dependencies as Inversion
of Control Containers, and soon, the meaning of IoC gradually drifted towards that particular meaning: Inversion of Control over Dependencies.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.
source
IoC (Inversion of Control) :- It’s a generic term and implemented in several ways (events, delegates etc).
DI (Dependency Injection) :- DI is a sub-type of IoC and is implemented by constructor injection, setter injection or Interface injection.
But, Spring supports only the following two types :
Setter Injection
Setter-based DI is realized by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.
Constructor Injection
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.Using this we can validate that the injected beans are not null and fail fast(fail on compile time and not on run-time), so while starting application itself we get NullPointerException: bean does not exist. Constructor injection is Best practice to inject dependencies.
DI is a subset of IoC
IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service). 2 implementations of IoC, I use, are DI and ServiceLocator.
DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn't depend on lower level component, only from the interface. Mocks implement these interfaces.
Here are some other techniques to achieve IoC.
IOC (Inversion Of Control): Giving control to the container to get an instance of the object is called Inversion of Control, means instead of you are creating an object using the new operator, let the container do that for you.
DI (Dependency Injection): Way of injecting properties to an object is called Dependency Injection.
We have three types of Dependency Injection:
Constructor Injection
Setter/Getter Injection
Interface Injection
Spring supports only Constructor Injection and Setter/Getter Injection.
Since all the answers emphasize on theory I would like to demonstrate with an example first approach:
Suppose we are building an application which contains a feature to send SMS confirmation messages once the order has been shipped.
We will have two classes, one is responsible for sending the SMS (SMSService), and another responsible for capturing user inputs (UIHandler), our code will look as below:
public class SMSService
{
public void SendSMS(string mobileNumber, string body)
{
SendSMSUsingGateway(mobileNumber, body);
}
private void SendSMSUsingGateway(string mobileNumber, string body)
{
/*implementation for sending SMS using gateway*/
}
}
public class UIHandler
{
public void SendConfirmationMsg(string mobileNumber)
{
SMSService _SMSService = new SMSService();
_SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
}
}
Above implementation is not wrong but there are few issues:
-) Suppose On development environment, you want to save SMSs sent to a text file instead of using SMS gateway, to achieve this; we will end up changing the concrete implementation of (SMSService) with another implementation, we are losing flexibility and forced to rewrite the code in this case.
-) We’ll end up mixing responsibilities of classes, our (UIHandler) should never know about the concrete implementation of (SMSService), this should be done outside the classes using “Interfaces”. When this is implemented, it will give us the ability to change the behavior of the system by swapping the (SMSService) used with another mock service which implements the same interface, this service will save SMSs to a text file instead of sending to mobileNumber.
To fix the above issues we use Interfaces which will be implemented by our (SMSService) and the new (MockSMSService), basically the new Interface (ISMSService) will expose the same behaviors of both services as the code below:
public interface ISMSService
{
void SendSMS(string phoneNumber, string body);
}
Then we will change our (SMSService) implementation to implement the (ISMSService) interface:
public class SMSService : ISMSService
{
public void SendSMS(string mobileNumber, string body)
{
SendSMSUsingGateway(mobileNumber, body);
}
private void SendSMSUsingGateway(string mobileNumber, string body)
{
/*implementation for sending SMS using gateway*/
Console.WriteLine("Sending SMS using gateway to mobile:
{0}. SMS body: {1}", mobileNumber, body);
}
}
Now we will be able to create new mock up service (MockSMSService) with totally different implementation using the same interface:
public class MockSMSService :ISMSService
{
public void SendSMS(string phoneNumber, string body)
{
SaveSMSToFile(phoneNumber,body);
}
private void SaveSMSToFile(string mobileNumber, string body)
{
/*implementation for saving SMS to a file*/
Console.WriteLine("Mocking SMS using file to mobile:
{0}. SMS body: {1}", mobileNumber, body);
}
}
At this point, we can change the code in (UIHandler) to use the concrete implementation of the service (MockSMSService) easily as below:
public class UIHandler
{
public void SendConfirmationMsg(string mobileNumber)
{
ISMSService _SMSService = new MockSMSService();
_SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
}
}
We have achieved a lot of flexibility and implemented separation of concerns in our code, but still we need to do a change on the code base to switch between the two SMS Services. So we need to implement Dependency Injection.
To achieve this, we need to implement a change to our (UIHandler) class constructor to pass the dependency through it, by doing this, the code which uses the (UIHandler) can determine which concrete implementation of (ISMSService) to use:
public class UIHandler
{
private readonly ISMSService _SMSService;
public UIHandler(ISMSService SMSService)
{
_SMSService = SMSService;
}
public void SendConfirmationMsg(string mobileNumber)
{
_SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
}
}
Now the UI form which will talk with class (UIHandler) is responsible to pass which implementation of interface (ISMSService) to consume. This means we have inverted the control, the (UIHandler) is no longer responsible to decide which implementation to use, the calling code does. We have implemented the Inversion of Control principle which DI is one type of it.
The UI form code will be as below:
class Program
{
static void Main(string[] args)
{
ISMSService _SMSService = new MockSMSService(); // dependency
UIHandler _UIHandler = new UIHandler(_SMSService);
_UIHandler.SendConfirmationMsg("96279544480");
Console.ReadLine();
}
}
Rather than contrast DI and IoC directly, it may be helpful to start from the beginning: every non-trivial application depends on other pieces of code.
So I am writing a class, MyClass, and I need to call a method of YourService... somehow I need to acquire an instance of YourService. The simplest, most straightforward way is to instantiate it myself.
YourService service = new YourServiceImpl();
Direct instantiation is the traditional (procedural) way to acquire a dependency. But it has a number of drawbacks, including tight coupling of MyClass to YourServiceImpl, making my code difficult to change and difficult to test. MyClass doesn't care what the implementation of YourService looks like, so MyClass doesn't want to be responsible for instantiating it.
I'd prefer to invert that responsibility from MyClass to something outside MyClass. The simplest way to do that is just to move the instantiation call (new YourServiceImpl();) into some other class. I might name this other class a Locator, or a Factory, or any other name; but the point is that MyClass is no longer responsible for YourServiceImpl. I've inverted that dependency. Great.
Problem is, MyClass is still responsible for making the call to the Locator/Factory/Whatever. Since all I've done to invert the dependency is insert a middleman, now I'm coupled to the middleman (even if I'm not coupled to the concrete objects the middleman gives me).
I don't really care where my dependencies come from, so I'd prefer not to be responsible for making the call(s) to retrieve them. Inverting the dependency itself wasn't quite enough. I want to invert control of the whole process.
What I need is a totally separate piece of code that MyClass plugs into (call it a framework). Then the only responsibility I'm left with is to declare my dependency on YourService. The framework can take care of figuring out where and when and how to get an instance, and just give MyClass what it needs. And the best part is that MyClass doesn't need to know about the framework. The framework can be in control of this dependency wiring process. Now I've inverted control (on top of inverting dependencies).
There are different ways of connecting MyClass into a framework. Injection is one such mechanism whereby I simply declare a field or parameter that I expect a framework to provide, typically when it instantiates MyClass.
I think the hierarchy of relationships among all these concepts is slightly more complex than what other diagrams in this thread are showing; but the basic idea is that it is a hierarchical relationship. I think this syncs up with DIP in the wild.
But the spring documentation says they are same.
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-introduction
In the first line "IoC is also known as dependency injection (DI)".
IoC - Inversion of control is generic term, independent of language, it is actually not create the objects but describe in which fashion object is being created.
DI - Dependency Injection is concrete term, in which we provide dependencies of the object at run time by using different injection techniques viz. Setter Injection, Constructor Injection or by Interface Injection.
Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality.
There are several basic techniques to implement inversion of control. These are:
Using a factory pattern
Using a service locator pattern
Using a dependency injection of any given below type:
1). A constructor injection
2). A setter injection
3). An interface injection
Inversion of Control is a generic design principle of software architecture that assists in creating reusable, modular software frameworks that are easy to maintain.
It is a design principle in which the Flow of Control is "received" from the generic-written library or reusable code.
To understand it better, lets see how we used to code in our earlier days of coding. In procedural/traditional languages, the business logic generally controls the flow of the application and "Calls" the generic or reusable code/functions. For example, in a simple Console application, my flow of control is controlled by my program's instructions, that may include the calls to some general reusable functions.
print ("Please enter your name:");
scan (&name);
print ("Please enter your DOB:");
scan (&dob);
//More print and scan statements
<Do Something Interesting>
//Call a Library function to find the age (common code)
print Age
In Contrast, with IoC, the Frameworks are the reusable code that "Calls" the business logic.
For example, in a windows based system, a framework will already be available to create UI elements like buttons, menus, windows and dialog boxes. When I write the business logic of my application, it would be framework's events that will call my business logic code (when an event is fired) and NOT the opposite.
Although, the framework's code is not aware of my business logic, it will still know how to call my code. This is achieved using events/delegates, callbacks etc. Here the Control of flow is "Inverted".
So, instead of depending the flow of control on statically bound objects, the flow depends upon the overall object graph and the relations between different objects.
Dependency Injection is a design pattern that implements IoC principle for resolving dependencies of objects.
In simpler words, when you are trying to write code, you will be creating and using different classes. One class (Class A) may use other classes (Class B and/or D). So, Class B and D are dependencies of class A.
A simple analogy will be a class Car. A car might depend on other classes like Engine, Tyres and more.
Dependency Injection suggests that instead of the Dependent classes (Class Car here) creating its dependencies (Class Engine and class Tyre), class should be injected with the concrete instance of the dependency.
Lets understand with a more practical example. Consider that you are writing your own TextEditor. Among other things, you can have a spellchecker that provides the user with a facility to check the typos in his text. A simple implementation of such a code can be:
Class TextEditor
{
//Lot of rocket science to create the Editor goes here
EnglishSpellChecker objSpellCheck;
String text;
public void TextEditor()
{
objSpellCheck = new EnglishSpellChecker();
}
public ArrayList <typos> CheckSpellings()
{
//return Typos;
}
}
At first sight, all looks rosy. The user will write some text. The developer will capture the text and call the CheckSpellings function and will find a list of Typos that he will show to the User.
Everything seems to work great until one fine day when one user starts writing French in the Editor.
To provide the support for more languages, we need to have more SpellCheckers. Probably French, German, Spanish etc.
Here, we have created a tightly-coupled code with "English"SpellChecker being tightly coupled with our TextEditor class, which means our TextEditor class is dependent on the EnglishSpellChecker or in other words EnglishSpellCheker is the dependency for TextEditor. We need to remove this dependency. Further, Our Text Editor needs a way to hold the concrete reference of any Spell Checker based on developer's discretion at run time.
So, as we saw in the introduction of DI, it suggests that the class should be injected with its dependencies. So, it should be the calling code's responsibility to inject all the dependencies to the called class/code. So we can restructure our code as
interface ISpellChecker
{
Arraylist<typos> CheckSpelling(string Text);
}
Class EnglishSpellChecker : ISpellChecker
{
public override Arraylist<typos> CheckSpelling(string Text)
{
//All Magic goes here.
}
}
Class FrenchSpellChecker : ISpellChecker
{
public override Arraylist<typos> CheckSpelling(string Text)
{
//All Magic goes here.
}
}
In our example, the TextEditor class should receive the concrete instance of ISpellChecker type.
Now, the dependency can be injected in Constructor, a Public Property or a method.
Lets try to change our class using Constructor DI. The changed TextEditor class will look something like:
Class TextEditor
{
ISpellChecker objSpellChecker;
string Text;
public void TextEditor(ISpellChecker objSC)
{
objSpellChecker = objSC;
}
public ArrayList <typos> CheckSpellings()
{
return objSpellChecker.CheckSpelling();
}
}
So that the calling code, while creating the text editor can inject the appropriate SpellChecker Type to the instance of the TextEditor.
You can read the complete article here
DI and IOC are two design pattern that mainly focusing on providing loose coupling between components, or simply a way in which we decouple the conventional dependency relationships between object so that the objects are not tight to each other.
With following examples, I am trying to explain both these concepts.
Previously we are writing code like this
Public MyClass{
DependentClass dependentObject
/*
At somewhere in our code we need to instantiate
the object with new operator inorder to use it or perform some method.
*/
dependentObject= new DependentClass();
dependentObject.someMethod();
}
With Dependency injection, the dependency injector will take care of the instantiation of objects
Public MyClass{
/* Dependency injector will instantiate object*/
DependentClass dependentObject
/*
At somewhere in our code we perform some method.
The process of instantiation will be handled by the dependency injector
*/
dependentObject.someMethod();
}
The above process of giving the control to some other (for example the container) for the instantiation and injection can be termed as Inversion of Control and the process in which the IOC container inject the dependency for us can be termed as dependency injection.
IOC is the principle where the control flow of a program is inverted: instead of the programmer controlling the flow of a program, program controls the flow by reducing the overhead to the programmer.and the process used by the program to inject dependency is termed as DI
The two concepts work together providing us with a way to write much more flexible, reusable, and encapsulated code, which make them as important concepts in designing object-oriented solutions.
Also Recommend to read.
What is dependency injection?
You can also check one of my similar answer here
Difference between Inversion of Control & Dependency Injection
IOC(Inversion Of Control): Giving control to the container to get instance of object is called Inversion of Control. It means instead of you are creating object using new operator, let the container do that for you.
DI(Dependency Injection): Passing the required parameters(properties) from XML to an object(in POJO CLASS) is called Dependency injection.
IOC indicates that an external classes managing the classes of an application,and external classes means a container manages the dependency between class of application.
basic concept of IOC is that programmer don't need to create your objects but describe how they should be created.
The main tasks performed by IoC container are:
to instantiate the application class. to configure the object. to assemble the dependencies between the objects.
DI is the process of providing the dependencies of an object at run time by using setter injection or constructor injection.
IOC - DIP - DI
Inversion of Control (IOC)
Dependency Inversion Principle (DIP)
Dependency Injection (DI)
1- IOC: abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.
2-DIP: is Object Oriented Programming(OOP) principle(D of SOLID).
3-DI: is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle.
IOC & DIP are two disjoint sets and DIP is the super set of DI, service locator and some other patterns
IOC (Inversion of Control) is basically design pattern concept of removing dependencies and decoupling them to making the flow non-linear , and let the container / or another entity manage the provisioning of dependencies. It actually follow Hollywood principal “Don’t call us we will call you”.
So summarizing the differences.
Inversion of control :- It’s a generic term to decouple the dependencies and delegate their provisioning , and this can be implemented in several ways (events, delegates etc).
Dependency injection :- DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.
The following article describe this very neatly.
https://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-Inversion-of-Control-IO
I think the idea can be demonstrated clearly without getting into Object Oriented weeds, which seem to muddle the idea.
// dependency injection
function doSomething(dependency) {
// do something with your dependency
}
// in contrast to creating your dependencies yourself
function doSomething() {
dependency = getDependencySomehow()
}
// inversion of control
application = makeApp(authenticate, handleRequest, sendResponse)
application.run(getRequest())
// in contrast to direct control or a "library" style
application = makeApp()
request = application.getRequest()
if (application.authenticate(request.creds)) {
response = application.handleRequest(request)
application.sendResponse(response)
}
If you tilt your head and squint your eyes, you'll see that DI is a particular implementation of IoC with specific concerns. Instead of injecting models and behaviors into an application framework or higher-order operation, you are injecting variables into a function or object.
Let's begin with D of SOLID and look at DI and IoC from Scott Millett's book "Professional ASP.NET Design Patterns":
Dependency Inversion Principle (DIP)
The DIP is all about isolating your classes from concrete
implementations and having them depend on abstract classes or
interfaces. It promotes the mantra of coding to an interface rather
than an implementation, which increases flexibility within a system by
ensuring you are not tightly coupled to one implementation.
Dependency Injection (DI) and Inversion of Control (IoC)
Closely linked to the DIP are the DI principle and the IoC principle. DI is the act of supplying a low level or dependent class via a
constructor, method, or property. Used in conjunction with DI, these
dependent classes can be inverted to interfaces or abstract classes
that will lead to loosely coupled systems that are highly testable and
easy to change.
In IoC, a system’s flow of control is inverted
compared to procedural programming. An example of this is an IoC
container, whose purpose is to inject services into client code
without having the client code specifying the concrete implementation.
The control in this instance that is being inverted is the act of the
client obtaining the service.
Millett,C (2010). Professional ASP.NET Design Patterns. Wiley Publishing. 7-8.
DIP vs DI vs IoC
[Dependency Inversion Principle(DIP)] is a part of SOLID[About] which ask you to use abstraction instead of realizations
Dependency Injection(DI) - use Aggregation instead of Composition[About] In this case external object is responsible for logic inside. Which allows you to have more dynamic and testable approach
class A {
B b
//injecting B via constructor
init(b: B) {
self.b = b
}
}
Inversion of Control(IoC) very high level definition which is more about control flow. The best example is Inversion of Control(IoC) Container or Framework[About]. For example GUI which is Framework where you don't have a control, everything which you can do is just implement Framework's interface which will be called when some action is happend in the Framework. So control is shifted from your application into the Framework being used
DIP + DI
class A {
IB ib
init(ib: IB) {
self.ib = ib
}
}
Also you can achieve it using:
[Factory Method]
[Service Locator]
[IoC-container(framework)]
More complex example
Dependency rule in multi layer/module structure
Pseudocode:
interface InterfaceInputPort {
func input()
}
interface InterfaceOutputPort {
func output()
}
class A: InterfaceOutputPort {
let inputPort = B(outputPort: self)
func output() {
print("output")
}
}
class B: InterfaceInputPort {
let outputPort: InterfaceOutputPort
init(outputPort: InterfaceOutputPort) {
self.outputPort = outputPort
}
func input() {
print("input")
}
}
//ICO , DI ,10 years back , this was they way:
public class AuditDAOImpl implements Audit{
//dependency
AuditDAO auditDAO = null;
//Control of the AuditDAO is with AuditDAOImpl because its creating the object
public AuditDAOImpl () {
this.auditDAO = new AuditDAO ();
}
}
Now with Spring 3,4 or latest its like below
public class AuditDAOImpl implements Audit{
//dependency
//Now control is shifted to Spring. Container find the object and provide it.
#Autowired
AuditDAO auditDAO = null;
}
Overall the control is inverted from old concept of coupled code to the frameworks like Spring which makes the object available. So that's IOC as far as I know and Dependency injection as you know when we inject the dependent object into another object using Constructor or setters . Inject basically means passing it as an argument. In spring we have XML & annotation based configuration where we define bean object and pass the dependent object with Constructor or setter injection style.
I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI
“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control.,
means instead of you are creating object using new operator, let the container do that for you.
DI(Dependency Injection): Way of injecting properties to an object is
called
Dependency injection.
We have three types of Dependency injection
1) Constructor Injection
2) Setter/Getter Injection
3) Interface Injection
Spring will support only Constructor Injection and Setter/Getter Injection.
Read full article IOC and Read Full article DI
1) DI is Child->obj depends on parent-obj. The verb depends is important.
2) IOC is Child->obj perform under a platform. where platform could be school, college, dance class. Here perform is an activity with different implication under any platform provider.
practical example:
`
//DI
child.getSchool();
//IOC
child.perform()// is a stub implemented by dance-school
child.flourish()// is a stub implemented by dance-school/school/
`
-AB
As for this question, I'd say the wiki has already provided detailed and easy-understanding explanations. I will just quote the most significant here.
Implementation of IoC
In object-oriented programming, there are several basic techniques to
implement inversion of control. These are:
Using a service locator pattern Using dependency injection, for
example Constructor injection Parameter injection Setter injection
Interface injection;
Using a contextualized lookup;
Using template method design pattern;
Using strategy design pattern
As for Dependency Injection
dependency injection is a technique whereby one object (or static
method) supplies the dependencies of another object. A dependency is
an object that can be used (a service). An injection is the passing of
a dependency to a dependent object (a client) that would use it.
IoC concept was initially heard during the procedural programming era. Therefore from a historical context IoC talked about inversion of the ownership of control-flow i.e. who owns the responsibility to invoke the functions in the desired order - whether it's the functions themselves or should you invert it to some external entity.
However once the OOP emerged, people began to talk about IoC in OOP context where applications are concerned with object creation and their relationships as well, apart from the control-flow. Such applications wanted to invert the ownership of object-creation (rather than control-flow) and required a container which is responsible for object creation, object life-cycle & injecting dependencies of the application objects thereby eliminating application objects from creating other concrete object.
In that sense DI is not the same as IoC, since it's not about control-flow, however it's a kind of Io*, i.e. Inversion of ownership of object-creation.
What is wrong in my way of explainning DI and IoC?

Repository Pattern in asp.net mvc with linq to sql

I have been reading though the code of the NerdDinner app and specifically the Repository Pattern...
I have one simple question though, regarding this block
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
What if each Dinner also had, say, a Category... my question is
Would you also initialize the category Repository in the constructor of the class??
Im sure it would work but Im not sure if the correct way would be to initialize the repository inside the method that is going to use that repository or just in the constructor of the class??
I would appreciate some insight on this issue
Thanks.
What you're looking at here is actually not so much to do with the repository pattern, per se, and more to do with "dependency injection," where the outside things on which this class depends are "injected" from without, rather rather than instantiated within (by calling new Repository(), for example).
This specific example shows "constructor injection," where the dependencies are injected when the object is created. This is handy because you can always know that the object is in a particular state (that it has a repository implementation). You could just as easily use property injection, where you provide a public setter for assigning the repository or other dependency. This forfeits the stated advantage of constructor injection, and is somewhat less clear when examining the code, but an inversion-of-control container can handle the work of instantiating objects and injecting dependencies in the constructor and/or properties.
This fosters proper encapsulation and improves testability substantially.
The fact that you aren't instantiating collaborators within the class is what improves testability (you can isolate the behaviour of a class by injecting stub or mock instances when testing).
The key word here when it comes to the repository pattern is encapsulation. The repository pattern takes all that data access stuff and hides it from the classes consuming the repository. Even though an ORM might be hiding all the actual CRUD work, you're still bound to the ORM implementation. The repository can act as a facade or adapter -- offering an abstract interface for accessing objects.
So, when you take these concepts together, you have a controller class that does not handle data access itself and does not instantiate a repository to handle it. Rather the controller accepts an injected repository, and knows only the interface. What is the benefit? That you can change your data access entirely and never ever touch the controller.
Getting further to your question, the repository is a dependency, and it is being provided in the constructor for the reasons outlined above. If you have a further dependency on a CategoryRepository, then yes, by all means inject that in the constructor as well.
Alternatively, you can provide factory classes as dependencies -- again classes that implement some factory interface, but instead of the dependency itself, this is a class that knows how to create the dependency. Maybe you want a different IDinnerRepository for different situations. The factory could accept a parameter and return an implementation according to some logic, and since it will always be an IDinnerRepository, the controller needs be none the wiser about what that repository is actually doing.
To keep your code decoupled and your controllers easily testable you need to stick with dependency injection so either:
public DinnersController()
: this(new DinnerRepository(), new CategoryRepository()) {
}
or the less elegant
public DinnersController()
: this(new DinnerRepository(new CategoryRepository())) {
}
I would have my dinner categories in my dinner repository personally. But if they had to be seperate the id put them both in the ctor.
You'd want to pass it in to the constructor. That said, I probably wouldn't create any concrete class like it's being done there.
I'm not familiar with the NerdDinner app, but I think the preferred approach is to define an IDinnerRepository (and ICategoryRepository). If you code against interfaces and wanted to switch to say, an xml file, MySQL database or a web service you would not need to change your controller code.
Pushing this out just a little further, you can look at IoC containers like ninject. The gist of it is is that you map your IDinnerRepository to a concrete implementation application wide. Then whenever a controller is created, the concrete repository (or any other dependency you might need) is provided for you even though you're coding against an interface.
It depends on whether you will be testing your Controllers (, which you should be doing). Passing the repositories in by the constructor, and having them automatically injected by your IOC container, is combining convenience with straightforward testing. I would suggest putting all needed repositories in the constructor.
If you seem to have a lot of different repositories in your constructors, it might be a sign that your controller is trying to do too many unrelated things. Might; sometimes using multiple repositories is legitimate.
Edit in response to comment:
A lot of repositories in one controller constructor might be considered a bad code smell, but a bad smell is not something wrong; it is something to look at because there might be something wrong. If you determine that having these activities handled in the same controller makes for the highest overall simplicity in your solution, then do that, with as many repositories as you need in the constructor.
I can use myself as an example as to why many repositories in a controller is a bad smell. I tend to get too cute, trying to do too many things on a page or controller. I always get suspicious when I see myself putting a lot of repositories in the constructor, because I sometimes do try to cram too much into a controller. That doesn't mean it's necessarily bad. Or, maybe the code smell does indicate a deeper problem, but it not one that is too horrible, you can fix it right now, and maybe you won't ever fix it: not the end of the world.
Note: It can help minimize repositories when you have one repository per Aggregate root, rather than per Entity class.

Why not pass your IoC container around?

On this AutoFac "Best Practices" page (http://code.google.com/p/autofac/wiki/BestPractices), they say:
Don't Pass the Container Around
Giving components access to the container, or storing it in a public static property, or making functions like Resolve() available on a global 'IoC' class defeats the purpose of using dependency injection. Such designs have more in common with the Service Locator pattern.
If components have a dependency on the container, look at how they're using the container to retrieve services, and add those services to the component's (dependency injected) constructor arguments instead.
So what would be a better way to have one component "dynamically" instantiate another? Their second paragraph doesn't cover the case where the component that "may" need to be created will depend on the state of the system. Or when component A needs to create X number of component B.
To abstract away the instantiation of another component, you can use the Factory pattern:
public interface IComponentBFactory
{
IComponentB CreateComponentB();
}
public class ComponentA : IComponentA
{
private IComponentBFactory _componentBFactory;
public ComponentA(IComponentBFactory componentBFactory)
{
_componentBFactory = componentBFactory;
}
public void Foo()
{
var componentB = _componentBFactory.CreateComponentB();
...
}
}
Then the implementation can be registered with the IoC container.
A container is one way of assembling an object graph, but it certainly isn't the only way. It is an implementation detail. Keeping the objects free of this knowledge decouples them from infrastructure concerns. It also keeps them from having to know which version of a dependency to resolve.
Autofac actually has some special functionality for exactly this scenario - the details are on the wiki here: http://code.google.com/p/autofac/wiki/DelegateFactories.
In essence, if A needs to create multiple instances of B, A can take a dependency on Func<B> and Autofac will generate an implementation that returns new Bs out of the container.
The other suggestions above are of course valid - Autofac's approach has a couple of differences:
It avoids the need for a large number of factory interfaces
B (the product of the factory) can still have dependencies injected by the container
Hope this helps!
Nick
An IoC takes the responsibility for determining which version of a dependency a given object should use. This is useful for doing things like creating chains of objects that implement an interface as well as having a dependency on that interface (similar to a chain of command or decorator pattern).
By passing your container, you are putting the onus on the individual object to get the appropriate dependency, so it has to know how to. With typical IoC usage, the object only needs to declare that it has a dependency, not think about selecting between multiple available implementations of that dependency.
Service Locator patterns are more difficult to test and it certainly is more difficult to control dependencies, which may lead to more coupling in your system than you really want.
If you really want something like lazy instantiation you may still opt for the Service Locator style (it doesn't kill you straight away and if you stick to the container's interface it is not too hard to test with some mocking framework). Bear in mind, though that the instantiation of a class that doesn't do much (or anything) in the constructor is immensely cheap.
The container's I have come to know (not autofac so far) will let you modify what dependencies should be injected into which instance depending on the state of the system such that even those decisions can be externalized into the configuration of the container.
This can provide you plenty of flexibility without resorting to implementing interaction with the container based on some state you access in the instance consuming dependencies.

Resources