Dependency Injection
Advantages of Dependency Injection:
- · Reduces class coupling
- · Increases code reusing
- · Improves code maintainability
- · Improves application testing
Popular DI containers?
Castle Windsor
·
Based on the Castle MicroKernel.
·
Well documented and used by many.
·
Understands Decorator
·
Typed factories
·
Commercial support available
Spring.NET
·
INTERCEPTION
·
Comprehensive documentation
·
Commercial support available
Autofac
·
Easy to learn API
·
second-generation DI Container
·
Commercial support available
Unity
·
INTERCEPTION
·
Good documentation
·
Consistent API
Ninject
·
Easy to learn API
·
Second-generation DI Container
Implementation of Dependency Injection Pattern in C#
Dependency Injection (DI) is a software design pattern that
allow us to develop loosely coupled code. DI is a great way to reduce tight
coupling between software components. DI also enables us to better manage
future changes and other complexity in our software. The purpose of DI is to make
code maintainable.
Constructor Injection
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
}
}
public class Client
{
private IService _service;
public Client(IService service)
{
_service = service;
}
public void Start()
{
_service.Serve();
}
}
internal class Program
{
private static void Main(string[] args)
{
Client client = new Client(new Service());
client.Start();
}
}
Property injection
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
}
}
public class Client
{
private IService _service;
public IService Service
{
set
{
_service = value;
}
}
public void Start()
{
_service.Serve();
}
}
internal class Program
{
private static void Main(string[] args)
{
Client client = new Client();
client.Service = new Service();
client.Start();
}
}
Method injection
public interface IService
{
void Serve();
}
public class Service : IService
{
public void Serve()
{
Console.WriteLine("Service Called");
}
}
public class Client
{
private IService _service;
public void Start(IService service)
{
_service = service;
_service.Serve();
}
}
internal class Program
{
private static void Main(string[] args)
{
Client client = new Client();
client.Start(new Service());
}
}
No comments:
Post a Comment