Articles → .NET DESIGN PATTERN → Property (Or Setter) Dependency Injection In C#

Property (Or Setter) Dependency Injection In C#






Purpose





NuGet Package Installation




Picture showing the Microsoft.Extensions.DependencyInjection package installed
Click to Enlarge


Create An Interface And A Class




public interface IDependency {
    void Display();
}

public class DependencyClass : IDependency {
    public void Display() {
        Console.WriteLine("Display Function Called");
    }
}



Create An Implementation Class




public class ImplementationClass {
    public IDependency Dependency { get; set; }

    public void WrapperDisplay() {
        Dependency.Display();
    }
}



Call The Implementation Class


// Create a new service collection
var services = new ServiceCollection();

// Configure the services
services.AddTransient<IDependency, DependencyClass>();
services.AddTransient<ImplementationClass>();

// Build the service provider
var serviceProvider = services.BuildServiceProvider();

// Resolve the ImplementationClass instance from the service provider
var implementation = serviceProvider.GetService<ImplementationClass>();
DependencyClass obj = new DependencyClass();
            
implementation.Dependency = obj;

implementation.WrapperDisplay();
Console.ReadLine();



Output


Picture showing the output of Property (Or Setter) Dependency Injection In C#
Click to Enlarge


Full Code


using Microsoft.Extensions.DependencyInjection;
using System;

namespace PropertyDependencyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new service collection
            var services = new ServiceCollection();

            // Configure the services
            services.AddTransient<IDependency, DependencyClass>();
            services.AddTransient<ImplementationClass>();

            // Build the service provider
            var serviceProvider = services.BuildServiceProvider();

            // Resolve the ImplementationClass instance from the service provider
            var implementation = serviceProvider.GetService<ImplementationClass>();
            DependencyClass obj = new DependencyClass();
            
            implementation.Dependency = obj;

            implementation.WrapperDisplay();
            Console.ReadLine();
        }
    }

    public interface IDependency {
        void Display();
    }

    public class DependencyClass : IDependency {
        public void Display() {
            Console.WriteLine("Display Function Called");
        }
    }

    public class ImplementationClass {
        public IDependency Dependency { get; set; }

        public void WrapperDisplay() {
            Dependency.Display();
        }
    }
}





Posted By  -  Karan Gupta
 
Posted On  -  Monday, July 10, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250