I am trying to understand Difference between Dependency Injection and Repository Pattern.
According to my understanding Repository Pattern does everything which Dependency Injection is doing, except in Dependency Injection we are using Constructor Injection.
Ok, Let me try to explain giving an example: (Please note I am using Unity Framework for DI)
Create Product Class
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Create Interface on Model
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
Implement Interface
//ProductRepository.cs
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
// Add products for the Demonstration
Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
}
public IEnumerable GetAll()
{
// TO DO : Code to get the list of all the records in database
return products;
}
public Product Get(int id)
{
// TO DO : Code to find a record in database
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// TO DO : Code to save record into database
item.Id = _nextId++;
products.Add(item);
return item;
}
public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// TO DO : Code to update record into database
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(item);
return true;
}
public bool Delete(int id)
{
// TO DO : Code to remove the records from database
products.RemoveAll(p => p.Id == id);
return true;
}
}
For DI Initialize Dependency in Bootstrap.cs
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<IProductRepository, ProductRepository>();
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
Controller
public class ProductController : Controller
{
readonly IProductRepository repository;
//inject dependency
public ProductController(IProductRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var data = repository.GetAll();
return View(data);
}
//Other Code
}
My Questions
Source of code: http://www.dotnet-tricks.com/Tutorial/dependencyinjection/632V140413-Dependency-Injection-in-ASP.NET-MVC-4-using-Unity-IoC-Container.html
They really aren't comparable a repository is something you can inject via dependency injection. The aim of DI is to make your application loosely coupled. Rather than specify a concrete implementation you can specify an interface that defines a contract that an implementation must fulfil. That way you can more easily swap out the implementation.
Repository pattern as defined by Martin Fowler isolates your domain from caring about how storage is implemented so all objects retrieved can be treated like an in memory collection. You could have a repository based on a database, an XML file a text document or anything. The applications code itself doesn't care. This makes it very useful for testing hence the connection to TDD.
You pass in (inject) dependcies to a controller. These could be repositories, services or anything that your controller requires. Your IoC container wires all of this together at runtime. This in itself is very powerful we make use of DI heavily in a SaaS application where customers have their own implementations which are injected depending conditionally on the client.
I recommend you read Dependency Injection in .NET. Mark Seemann can explain this much better than me and is an excellent introduction to the hows and whys you should use DI and various IoC Containers e.g. Unity
What is difference between Repository Pattern and DI
I don't think there is a meaningful comparison you can make. They are both programming techniques, but they arise from very different considerations. (c.f. The Repository Pattern, Dependency Injection)
I guess you could say they are connected in this way: a data repository is an example of an external dependency that your DI framework would typically inject into objects that need it.
What is advantage of Constructory Injection
Do you mean, as opposed to other injection patterns? Then: constructor injection allows you access to the injected dependencies when the object is first initialized.
Or do you mean, what is the advantage of using DI in general? This is a very broad question, but I'd say: coherent structure for your application, and less rigid coupling between its components.
Appreciate If someone can explain Bootstrap.cs file code and Controller class code with maximum possible details.
The "Bootstrapper" class in Unity, similarly to the "Kernel" class in Ninject, implements the DI pattern's so-called "composition layer". This is where you tell your DI container how it should resolve all the dependencies it will find throughout your application. This basically means matching up injected interfaces to their implementations, and providing instructions as to the scope of the injected objects (ie, singleton, per request, or transient).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With