What is Dependency Injection ?
Dependency Injection is a software design pattern. It allows us to develop loosely-coupled code. The intent of Dependency Injection is to make code maintainable. Dependency Injection helps to reduce the tight coupling among software components. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
Types of Dependency Injection in C#
1) Constructor Injection
2) Property Injection
3) Method Injection
1) Constructor Injection -
In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleProgram
{
public interface text
{
void print();
}
class format : text
{
public void print()
{
Console.WriteLine("this is text format");
}
}
// constructor injection
public class constructorinjection
{
private text _text;
public constructorinjection(text t1)
{
this._text = t1;
}
public void print()
{
_text.print();
}
}
class constructor
{
static void Main(string[] args)
{
constructorinjection cs = new constructorinjection(new format());
cs.print();
Console.ReadKey();
}
}
}
Output:-
this is text format
2) Property Injection-
In the property injection (aka the Setter Injection), the injector supplies the dependency through a public property of the client class.
public interface INofificationAction
{
void ActOnNotification(string message);
}
class sam {
INofificationAction task = null;
public void notify(INofificationAction at ,string messages)
{
this.task = at;
task.ActOnNotification(messages);
}
}
class EventLogWriter : INofificationAction
{
public void ActOnNotification(string message)
{
// Write to event log here
}
}
class Program
{
static void Main(string[] args)
{
//services srv = new services();
//other oth = new other();
//oth.run();
//Console.WriteLine();
EventLogWriter elw = new EventLogWriter();
sam sm = new sam ();
sm.notify(elw, "to logg");
Console.ReadKey();
}
}
You cannot control when the dependency is set at all, it can be changed at any point in the object's lifetime.
3) Method Injection-
the client class implements an interface which declares the method(s) to supply the dependency and the injector uses this interface to supply the dependency to the client class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleProgram
{
public interface Iset
{
void print();
}
public class servic : Iset
{
public void print()
{
Console.WriteLine("Print");
}
}
public class client
{
private Iset _set;
public void run(Iset serv)
{
this._set = serv;
Console.WriteLine("Hi");
this._set.print();
}
}
class method
{
public static void Main()
{
client cn = new client();
cn.run(new servic());
Console.ReadKey();
}
}
}
Output:-
Hi
Print
No comments:
Post a Comment