Search This Blog

Q16-Q20

Q16. When to use Property Dependency Injection over Constructor Injection and vice versa?
Q17. What is the relation between IOC, DIP, DI and IOC Container?
Q18. What are different types of IOC inversion of control Container?
Q19. What is JWT web token? Tell some features of JWT token?
Q20. I have an api which is capable of returning both xml and json data. From your client how you request so that data comes in XML format?

--------------------------------------------------------------------------------------------------------------------------
Q16. When to use Property Dependency Injection over Constructor Injection and vice versa?

Answer:
The Constructor Dependency Injection in C# is the standard for dependency injection. It ensures that all the dependency objects are initialized before we are going to invoke any methods or properties of the dependency object, as a result, it avoids the null reference exceptions.
The Setter/Property Dependency Injection in C# is rarely used in real-time applications. For example, if I have a class that has several methods but those methods do not depend on any other objects. Now I need to create a new method within the same class but that new method now depends on another object. If we use the constructor dependency injection here, then we need to change all the existing constructor calls where we created this class object. This can be a very difficult task if the project is a big one. Hence, in such scenarios, the Setter or Property Dependency Injection can be a good choice.
--------------------------------------------------------------------------------------------------------------------------
Q17. What is the relation between IOC, DIP, DI and IOC Container?

Answer:
IoC and DIP are high level design principles which should be used while designing application classes. As they are principles, they recommend certain best practices but do not provide any specific implementation details. Dependency Injection (DI) is a pattern and IoC container is a framework.

https://www.tutorialsteacher.com/ioc/introduction
--------------------------------------------------------------------------------------------------------------------------
Q18. What are different types of IOC inversion of control Container?

Answer:
There are a lot of Dependency Injection Containers are available in the market which implements the dependency injection design pattern. Some of the commonly used Dependency Injection Containers are as follows.
  1. Unity
  2. nInject
  3. Castle Windsor
  4. StructureMap
  5. Spring.NET
--------------------------------------------------------------------------------------------------------------------------
Q19. What is JWT web token? Tell some features of JWT token?

Answer:
  • JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object
  • Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token
  • Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
--------------------------------------------------------------------------------------------------------------------------
Q20. I have an api which is capable of returning both xml and json data. From your client how you request so that data comes in XML format?

Answer:
If our service need to support both the formats (XML/ JSON) then we need to add code in WebApiConfig.cs file. In order to accomplish  above requirement, we will force the user to send us information what type format they need.

http://localhost:1312/api/Blog?type=xml
http://localhost:1312/api/Blog?type=json


Search for text - "Send result in different formats like XML, JSON" in below url
https://www.c-sharpcorner.com/UploadFile/manas1/introduction-to-Asp-Net-webapi-and-returns-result-in-differe/
--------------------------------------------------------------------------------------------------------------------------

My Other Blogs

Q11-Q15

Q11. What is singleton design pattern?
Q12. What is Dependency Injection in C#. Why we need this?
Q13. Explain Constructor Dependency Injection.
Q14. Explain Property Dependency Injection. 
Q15. Explain Method Dependency Injection. 
--------------------------------------------------------------------------------------------------------------------------
Q11. What is singleton design pattern?

Answer:

Features of singleton design pattern are
  1. It Ensure that singleton class has only one instance, and provide a global point of access to it by its public property.
  2. Singleton class has private constructor to prevent it getting initiated by other classes.
  3. Singleton class has private static variable to hold single crated instance.
Practical example of singleton class
1. When you use Logger, you use Singleton pattern for the Logger class. In case it is not Singleton, every client will have its own Logger object and there will be concurrent access on the Logger instance in Multithreaded environment, and multiple clients will create/write to the Log file concurrently, this leads to data corruption.

2. second real life example of singleton pattern could be load balancer. 

Not thread safe implementation is below. it means if same code is running in multiple thread then it will create two more instance of singleton class. 

Singleton Class
     public class Singleton
    {
        // Use to hold the value of single instance but it will be accessible via public property
        private static Singleton _instance;

        // protect it from getting instantiated and inheited by other class
        private Singleton()
        {
            Console.WriteLine("Instance created");
        }

        public void Log(string message)
        {
            Console.WriteLine(message);
        }

        // global point of access to single created instance. 
        public static Singleton Instance
        {
            get
            {
                // Ensures only single instance can be created
                if (_instance == null)
                {
                    _instance = new Singleton();
                }

                return _instance;
            }
        }
    }

Main class
//Singleton s = new Singleton(); // error
            var s = Singleton.Instance;
            s.Log("super day");
            var a = Singleton.Instance;
            a.Log("next day");


output
--------------------------------------------------------------------------------------------------------------------------
Q12. What is Dependency Injection in C#. Why we need this?

Answer:
Dependency Injection is a software design pattern. It allows us to create a loosely coupled code.  This also make code more maintainable and testable. 
  • Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
We have 3 types of Dependency injection pattern
  1. Constructor Injection
  2. Property Injection
  3. Method Injection
Why we need this?

1. It make code more testable. 
2. Team-ability - Two persons can work independently instead of waiting for one to complete the code. 
3. Code maintenance - 
--------------------------------------------------------------------------------------------------------------------------
Q13. Explain Constructor Dependency Injection.

Answer:

Implementing without DI. 
create 3 classes Employee.cs, EmployeeDAL.cs and EmployeeBL.cs
Employee.cs

namespace DependencyInjectionExample
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}
EmployeeDAL.cs
  • namespace DependencyInjectionExample
  • {
  • public class EmployeeDAL
  • {
  • public List<Employee> SelectAllEmployees()
  • {
  • List<Employee> ListEmployees = new List<Employee>();
  • //Get the Employees from the Database
  • //for now we are hard coded the employees
  • ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
  • ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
  • ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
  • return ListEmployees;
  • }
  • }
  • }
EmployeeBL.cs

  • namespace DependencyInjectionExample
  • {
  • public class EmployeeBL
  • {
  • public EmployeeDAL employeeDAL;
  • public List<Employee> GetAllEmployees()
  • {
  • employeeDAL = new EmployeeDAL();
  • return employeeDAL.SelectAllEmployees();
  • }
  • }
  • }
In the above example, in order to get the data, the EmployeeBL class depends on the EmployeeDAL class. In the GetAllEmployees() method of the EmployeeBL class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke the SelectAllEmployees() method. This is tight coupling because the EmployeeDAL is tightly coupled with the EmployeeBL class. Every time the EmployeeDAL class changes, the EmployeeBL class also needs to change. 

use the constructor injection to make these classes loosely coupled.


Modify the EmployeeDAL.cs

  • namespace DependencyInjectionExample
  • {
  • public interface IEmployeeDAL
  • {
  • List<Employee> SelectAllEmployees();
  • }
  • public class EmployeeDAL : IEmployeeDAL
  • {
  • public List<Employee> SelectAllEmployees()
  • {
  • List<Employee> ListEmployees = new List<Employee>();
  • //Get the Employees from the Database
  • //for now we are hard coded the employees
  • ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
  • ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
  • ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
  • return ListEmployees;
  • }
  • }
  • }

Modify the EmployeeBL.cs file

  • namespace DependencyInjectionExample
  • {
  • public class EmployeeBL
  • {
  • public IEmployeeDAL employeeDAL;
  • public EmployeeBL(IEmployeeDAL employeeDAL)
  • {
  • this.employeeDAL = employeeDAL;
  • }
  • public List<Employee> GetAllEmployees()
  • {
  • Return employeeDAL.SelectAllEmployees();
  • }
  • }
  • }
In the above example, we created one constructor which accepts one parameter of the dependency object type. The point that you need to keep focus is, the parameter of the constructor is of the type interface, not the concrete class. Now, this parameter can accept any concrete class object which implements this interface.


Main method of Program class

  • namespace DependencyInjectionExample
  • {
  • class Program
  • {
  • static void Main(string[] args)
  • {
  • EmployeeBL employeeBL = new EmployeeBL(new EmployeeDAL());
  • List<Employee> ListEmployee = employeeBL.GetAllEmployees();
  • foreach(Employee emp in ListEmployee)
  • {
  • Console.WriteLine("ID = {0}, Name = {1}, Department = {2}", emp.ID, emp.Name, emp.Department);
  • }
  • Console.ReadKey();
  • }
  • }
  • }
https://dotnettutorials.net/lesson/dependency-injection-design-pattern-csharp/

--------------------------------------------------------------------------------------------------------------------------
Q14. Explain Property Dependency Injection. 

Answer:
This is also known as 'Setter' property injection. 

EmployeeBL.cs for property DI
  • namespace DependencyInjectionExample
  • {
  • public class EmployeeBL
  • {
  • private IEmployeeDAL employeeDAL;
  • public IEmployeeDAL employeeDataObject
  • {
  • set
  • {
  • this.employeeDAL = value;
  • }
  • get
  • {
  • if (employeeDataObject == null)
  • {
  • throw new Exception("Employee is not initialized");
  • }
  • else
  • {
  • return employeeDAL;
  • }
  • }
  • }
  • public List<Employee> GetAllEmployees()
  • {
  • return employeeDAL.SelectAllEmployees();
  • }
  • }
  • }
Main method of Program class as shown below to inject the object through a property
  • namespace DependencyInjectionExample
  • {
  • class Program
  • {
  • static void Main(string[] args)
  • {
  • EmployeeBL employeeBL = new EmployeeBL();
  • employeeBL.employeeDataObject = new EmployeeDAL();
  • List<Employee> ListEmployee = employeeBL.GetAllEmployees();
  • foreach(Employee emp in ListEmployee)
  • {
  • Console.WriteLine("ID = {0}, Name = {1}, Department = {2}", emp.ID, emp.Name, emp.Department);
  • }
  • Console.ReadKey();
  • }
  • }
  • }
https://dotnettutorials.net/lesson/setter-dependency-injection-design-pattern-csharp/

--------------------------------------------------------------------------------------------------------------------------
Q15. Explain Method Dependency Injection. 

Answer:
In Method Dependency Injection, we need to supply the dependency object through a public method of the client class. Let us see an example to understand how we can implement the Method dependency injection in C#.
Modify the EmployeeBL class as shown below

  • namespace DependencyInjectionExample
  • {
  • public class EmployeeBL
  • {
  • public IEmployeeDAL employeeDAL;
  • public List<Employee> GetAllEmployees(IEmployeeDAL _employeeDAL)
  • {
  • employeeDAL = _employeeDAL;
  • return employeeDAL.SelectAllEmployees();
  • }
  • }
  • }

Modify the Main method of Program class as shown below



  • namespace DependencyInjectionExample
  • {
  • class Program
  • {
  • static void Main(string[] args)
  • {
  • //Create object of EmployeeBL class
  • EmployeeBL employeeBL = new EmployeeBL();
  • //Call to GetAllEmployees method with proper object.
  • List<Employee> ListEmployee = employeeBL.GetAllEmployees(new EmployeeDAL());
  • foreach (Employee emp in ListEmployee)
  • {
  • Console.WriteLine("ID = {0}, Name = {1}, Department = {2}", emp.ID, emp.Name, emp.Department);
  • }
  • Console.ReadKey();
  • }
  • }
  • }
https://dotnettutorials.net/lesson/setter-dependency-injection-design-pattern-csharp/

--------------------------------------------------------------------------------------------------------------------------