Dependency injection is a technique to get rid of tightly coupled code.This session will give an idea about using DI in one's project with various patterns like constructor injection,setter injection and interface injection and demo of DI using Unity container.
3. Presenter: Kaveri Saxena, Mindfire Solutions
AGENDA
●Overview Of Dependency Injection
●Why Dependency Injection?
●Constructor Injection
●Setter Injection
●Interface Injection
●Overview of DI Containers
●Demo Implementing Dependency Injection with Unity Container
●Q&A
4. Overview Of Dependency Injection
Dependency injection is a software design pattern that allows
the removal of hard-coded dependencies and makes it possible
to change them,whether at run time or compile time.
Dependency injection is a set of software design principles and
Pattern that enable us to develop loosely coupled codes.
- Mark Seeman
Tight
Coupling
Form
(Class) Repository
Var repository = new Repository();
5. Why To Use DI?????
●Extensibility
●Testability
●Late Binding
●Parallel Development
●Maintainability
6. Constructor Injection
Pass dependency into dependent class via constructor
var service = new SQLService();
Var form = new PersonForm(service);
Application.Run(form);
private IServiceRepository Repository;
public PersonForm(IServiceRepository repository)
{
Repository = repository;
}
7. Setter Injection
Create a setter on the dependent class and use that to set the
dependency.
var form = new PersonForm();
form.Repository = new CSVService();
Application.Run(form);
private IServiceRepository Repository { get; set; }
8. Interface Injection
Dependent class implements an interface and injector uses
the interface to set the dependency.
var service = new SQLService();
var form = new PersonForm();
((IInjectInterface)form).inject(service);
Application.Run(form);
public interface IInjectInterface
{
void inject(IServiceRepository serviceRepo);
}
9. public partial class PersonForm :Form,IInjectInterface
{
public void inject(IServiceRepository serviceRepo)
{
Repository = serviceRepo;
}
}
10. Overview Of DI Container
●A framework for doing dependency Injection
●Configure dependencies
●Automatically resolves configured dependencies
Eg. Unity,Ninject,,CastleWindsor,Autofac,structuremap,
Spring.Net and many others.
SqlService
DI Container
CSVService
IService
Person Form
11. Unity Container
Unity comes from microsoft pattern and practice team,
available as free download.
For using Unity Container-
●Download compatible version of unity in your bootstrapper
Application
● Register interface with concrete type
●Call resolve method and unity will automatically find complex
constructor of dependent class and use concrete type instead
of interface.
var container = new UnityContainer();
container.RegisterType<IServiceRepository,
SQLService>();
var form = container.Resolve<PersonForm>();
Application.Run(form);