The main intension of the object-oriented programming is to manipulate real world objects and one of the features is reusability. There are many ways to get reusability and one of the easiest ways is ‘Inversion of Control’ in architectural patterns especially.
There are many techniques to implement ‘Inversion of Control’, find the following image for more conceptual view.
Now let’s talk about Dependency Injection. Here also same, we can Implement DI (Dependency Injection) with help of constructor, Property, Interface and Interface. This resource deals only Property Injection.
What is Injection and why it is helpful?
Injection is a technique to change object behavior at runtime.
Property Injection
Inject object through property properties with help of get and set.
Get a sample project and add Interface components to it, for more information
IdataActions is an Interface for method declarations.
- public interface IdataActions
- {
- void AddCustomerEntry(IdataProperties iDataProperties = null);
- }
IdataProperties for property declaration’s.
- public interface IdataProperties
- {
- string customerName { get; set;}
- int customerId { get; set; }
- string customerAddress { get; set; }
- }
Now let’s add
PropertyInjection.cs class to implement
IdataProperties and set to
property injection.
- public class PropertyInjection: IdataProperties
- {
- public IdataProperties iDataProperties
- {
- get
- {
- return new PropertyInjection();
- }
- }
- public string customerName
- {
- get
- {
- return "CustomerName";
- }
- set
- {
-
- }
- }
- public int customerId
- {
- get
- {
- return 123;
- }
- set
- {
-
- }
- }
- public string customerAddress
- {
- get
- {
- return "India";
- }
- set
- {
-
- }
- }
- }
Finally, implementation like the following,
- class Program: IdataActions
- {
- PropertyInjection propertyInjection = new PropertyInjection();
- public void AddCustomerEntry(IdataProperties iDataProperties = null)
- {
- if (iDataProperties == null)
- {
-
-
-
- iDataProperties = propertyInjection.iDataProperties;
- Console.WriteLine("customerId" + iDataProperties.customerId);
- Console.WriteLine("customerName" + iDataProperties.customerName);
- Console.WriteLine("customerAddress" + iDataProperties.customerAddress);
- }
- Console.WriteLine("Customer has been created");
- }
- static void Main(string[] args)
- {
- Program progrm = new Program();
- progrm.AddCustomerEntry();
- Console.Read();
- }
- }
Run and verify.