Thursday, April 9, 2020

Why do we have to make the GetInstance() method or Instance Property of a Singleton class Static?

Because the constructor of the singleton class is private and can't be accessed from the outside world. Therefore there is no other way for us to access the methods of this class than making it static.


Tuesday, July 28, 2015

What is an Assembly in C# .Net?

An assembly is the compiled output of your code, typically a DLL, but your EXE is also an assembly. It's the smallest unit of deployment for any .NET project.

The assembly typically contains .NET code in MSIL (Microsoft Intermediate language) that will be compiled to native code ("JITted" - compiled by the Just-In-Time compiler) the first time it is executed on a given machine. That compiled code will also be stored in the assembly and reused on subsequent calls.

The assembly can also contain resources like icons, bitmaps, string tables and so on. Furthermore, the assembly also contains metadata in the assembly manifest - information like version number, strong name, culture, referenced assemblies and so forth.

In 99% of your cases, one assembly equals a physical file on disk - the case of a multi-file assembly (one assembly, distributed across more than a single file) appears to be a rather odd-ball edge case

In a multifile assembly there would still be only one assembly manifest in a DLL or EXE and the MSIL code in multiple netmodule files. 

Monday, July 27, 2015

What are access modifiers in C#?

Access modifiers are keywords used to specify the declared accessibility of a member or a type.
 

Why to use access modifiers?

 
Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.
 
In C# there are 5 different types of Access Modifiers.
Modifier
Description
public
There are no restrictions on accessing public members.
private
Access is limited to within the class definition. This is the default access modifier type if none is formally specified
protected
Access is limited to within the class definition and any class that inherits from the class
internal
Access is limited exclusively to classes defined within the current project assembly
protected internal
Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

public
 
The public keyword is an access modifier for types and type members. Public access is the most permissive access level.
 
There are no restrictions on accessing public members.
 
Accessibility: 
  • Can be accessed by objects of the class
  • Can be accessed by derived classes
Example: In the following example num1 is direct access.
 
using System;
 
namespace AccessModifiers
{
    class Program
    {
        class AccessMod
        {
            public int num1;
        }
        static void Main(string[] args)
        {
            AccessMod ob1 = new AccessMod();
 
            //Direct access to public members
            ob1.num1 = 100;
 
            Console.WriteLine("Number one value in main {0}", ob1.num1);
            Console.ReadLine();
        }
    }
}
 
private
 
Private access is the least permissive access level.
 
Private members are accessible only within the body of the class or the struct in which they are declared.
 
Accessibility: 
  • Cannot be accessed by object
  • Cannot be accessed by derived classes
Example: In the following example num2 is not accessible outside the class.
 
using System;
 
namespace AccessModifiers
{
    class Program
    {
        class AccessMod
        {
            public int num1;
            int num2;
        }
        static void Main(string[] args)
        {
            AccessMod ob1 = new AccessMod();
 
            //Direct access to public members
            ob1.num1 = 100;
 
            //Access to private member is not permitted
 
            ob1.num2 = 20;
            Console.WriteLine("Number one value in main {0}", ob1.num1);
            Console.ReadLine();
        }
    }
}
 
The above program will give compilation error, as access to private is not permissible. In the below figure you can see the private member num2 is not available.

 
private.jpg
protected
 
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
 
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
 
Accessibility: 
  • Cannot be accessed by object
  • By derived classes
using System;
 
namespace AccessModifiers
{
    class Program
    {
        class Base
        {
            protected int num1;
        }
 
        class Derived : Base
        {
            public int num2;
            static void Main(string[] args)
            {
                Base ob1 = new Base();
                Derived ob2 = new Derived();
                ob2.num1 = 20;
 
                // Access to protected member as it is inhertited by the Derived class
                ob2.num2 = 90;
 
                Console.WriteLine("Number2 value {0}", ob2.num2);
                Console.WriteLine("Number1 value which is protected {0}", ob2.num1);
                Console.ReadLine();
            }
        }
    }
}
 
In the above program we try to access protected member in main it is not available as shown in the picture below that num1 is not listed in intellisense.

protected.jpg
 
internal
 
The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).
 
In other words, access is limited exclusively to classes defined within the current project assembly.
 
Accessibility:
 
In same assembly (public) 
  • Can be accessed by objects of the class
  • Can be accessed by derived classes
In other assembly (internal) 
  • Cannot be accessed by object
  • Cannot be accessed by derived classes
protected internal
 
The protected internal accessibility means protected OR internal, not protected AND internal.
 
In other words, a protected internal member is accessible from any class in the same assembly, including derived classes.
 
The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:  
  • Inherited types, even though they belong to a different assembly, have access to the protected internal members.
  • Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.

Default access

 
A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types:
 
enum: The default and only access modifier supported is public.
 
class: The default access for a class is private. It may be explicitly defined using any of the access modifiers.
 
interface: The default and only access modifier supported is public.
 
struct: The default access is private with public and internal supported as well.
 
The default access may suffice for a given situation, but you should specify the access modifier you want to use to ensure proper application behavior.
 
Note: Interface and enumeration members are always public and no access modifiers are allowed.

What is the difference between an abstract function and a virtual function?

An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.

A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.

Wednesday, July 22, 2015

What are the differences between Stored Procedure and a Trigger

  1. We can execute a stored procedure whenever we want with the help of the exec command, but a trigger can only be executed whenever an event (insert, delete, and update) is fired on the table on which the trigger is defined.
  2. We can call a stored procedure from inside another stored procedure but we can't directly call another trigger within a trigger. We can only achieve nesting of triggers in which the action (insert, delete, and update) defined within a trigger can initiate execution of another trigger defined on the same table or a different table.
  3. Stored procedures can be scheduled through a job to execute on a predefined time, but we can't schedule a trigger.
  4. Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.
  5. Stored procedures can return values but a trigger cannot return a value.
  6. We can use Print commands inside a stored procedure for debugging purposes but we can't use print commands inside a trigger.
  7. We can use transaction statements like begin transaction, commit transaction, and rollback inside a stored procedure but we can't use transaction statements inside a trigger.
  8. We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but we can't call a trigger from these files.
  9. Stored procedures are used for performing tasks. Stored procedures are normally used for performing user specified tasks. They can have parameters and return multiple results sets.
  10. The Triggers for auditing work: Triggers normally are used for auditing work. They can be used to trace the activities of table events.

What are the differences between Arrays and Collections

  • Arrays are fixed in size, therefore once we create an array we are not allowed to increase or decrease its size, based on the requirement. Collections are grow-able, therefore base on our requirement we can increase or decrease its size
  • Arrays use more memory space as compared to Collections
  • Performance point of view arrays are recommended (Faster), where as collections are not recommended
  • Arrays can hold only homogeneous elements, collections can hold both homogeneous and heterogeneous elements
  • Arrays can hold both primitives as well as objects, where as collection can not hold primitives (although they can store primitive wrapper classes such as Integer etc)
  • In Array , there are no underlined Data Structures, whereas ,Collection has Underlined DS

Monday, December 1, 2014

Difference and Similarities between class and structure?

DIFFERENCES

Class
  1. Class is a reference type and its object is created on the heap memory.
     
  2. Class can inherit the another class.
     
  3. Class can have the all types of constructor and destructor.
     
  4. The member variable of class can be initialized directly.
     
  5. class object can not be created without using the new keyword, it means we have to use it.

    Demo obj=new Demo();
Structure

  1. Structure is a value type that is why its object is created on the stack memory.
     
  2. Structure does not support the inheritance.
     
  3. Structure can only have the parametrized constructor. it means a structure can not have the non-parametrized constructor,default constructor and destructor also.
     
  4. The member variable of structure can not be initialized directly.
     
  5. Structure object can be created without using the new keyword.(optional) 



SIMILARITIES
  1. Both can have constructors, methods, properties, fields, constants, enumerations,
    events, and event handlers.
  2. Structures and classes can implement interface.
  3. Both can have delegates and events.

What are virtual classes?

Because a class can be an indirect base class to a derived class more than once, C++ provides a way to optimize the way such base classes work. Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritance.


Each nonvirtual object contains a copy of the data members defined in the base class. This duplication wastes space and requires you to specify which copy of the base class members you want whenever you access them.

When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use it as a virtual base.

When declaring a virtual base class, the virtual keyword appears in the base lists of the derived classes.

Why don’t C# and Java support multiple inheritance? What is wrong with multiple inheritance?

The main problem with multiple inheritance is that there can be times when the results of using multiple inheritance will be uncertain. The best example of this is the classic problem known as the Diamond Problem where a class inherits from 2 different classes, but those 2 different classes inherit from the same class, like in the graphic below (where class D derives from both classes B and C, and classes B and C both derive from class A:



And here is what the code for that example would look like:

class A {
           protected: 
               bool testing;
};

class B: public A { };

class C: public A { };

class D: public B, public C  {
  public:
    void setTesting ( bool xTesting)  {
            testing = xTesting; // this is uncertain
           }
};

In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.


But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:

B :: testing = xTesting;  // use B's version of testing

The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.

Alternatives to multiple inheritance

As you can probably see by now, having multiple inheritance built into a language can create problems. So, in the interest of keeping things simple, the creators of Java and C# decided not to allow multiple inheritance. However, there is an alternative to multiple inheritance, known as interfaces 

What is Multiple Inheritance?

C++ actually allows a class to inherit from more than one class, and this is referred to as multiple inheritance. But in C# and Java, classes are only allowed to inherit from a single parent class, which is called single inheritance.


Multiple inheritance allows people to create classes that combine aspects of different classes and their corresponding hierarchies. This is something that is quite common because applications often need to use the frameworks of different classes to achieve the desired functionality. Suppose that you are trying to create a class that models the animal known as a Liger, which is the result of having a Tiger and a Lion mate. Then you would create a class called Liger that derives from both the Tiger and Lion classes – so the Liger class would have to use multiple inheritance since it is deriving or inheriting from 2 different classes. 

Wednesday, September 3, 2014

What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Example

 public delegate int mydelegate(int delvar1,int delvar2)

Note


  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate 

delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void <place w:st="on" />Main</place />()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}

Tuesday, September 2, 2014

When to use custom control?

  • When you have a rapid and fixed content in your UI, use UserControl.
  • When you want to separate some basic functionality of your main view to some smaller pieces with reusability, use UserControl.
  • When you want to use your control in different projects and each project may want to change the look, use CustomControl.
  • When you want to implement some additional functionality for a control, create a CustomControl derived from the base control.
  • When you want to apply themes to your controls, use CustomControl.
  • When you want to add toolbox support for your control, so that your user will be able to do drag and drop to the designer, use CustomControl.

AJAX pros and cons

AJAX is rapidly becoming an integral part of several websites, several well established brands online now use AJAX to handle their web applications because it provides better interactivity to their users, this is due to the fact that implementing AJAX on a website, does not require a page to be reloaded for dynamic content on web pages. While there are numerous reasons to switch to AJAX there are quite a few matters that would make you reconsider using this combination of technologies as well. Below are some of the advantages and disadvantages of using AJAX.

Advantages

  • Better interactivity
    This is pretty much the most striking benefit behind why several developers and webmasters are switching to AJAX for their websites. AJAX allows easier and quicker interaction between user and website as pages are not reloaded for content to be displayed.
  • Easier navigation
    AJAX applications on websites can be built to allow easier navigation to users in comparison to using the traditional back and forward button on a browser.
  • Compact
    With AJAX, several multi purpose applications and features can be handled using a single web page, avoiding the need for clutter with several web pages. For our use of AJAX on goedkope-zomervakantie.com, it took just a few lines of code!
  • Backed by reputed brands
    Another assuring reason to use AJAX on your websites is the fact that several complex web applications are handled using AJAX, Google Maps is the most impressive and obvious example, other powerful, popular scripts such as the vBulletin forum software has also incorporated AJAX into their latest version.

Disadvantages


  • The back and refresh button are rendered useless
    With AJAX, as all functions are loaded on a dynamic page without the page being reloaded or more importantly a URL being changed (except for a hash symbol maybe), clicking the back or refresh button would take you to an entirely different web page or to the beginning of what your dynamic web page was processing. This is the main drawback behind AJAX but fortunately with good programming skills this issue can be fixed.
  • It is built on javascript
    While javascript is secure and has been heavily used by websites for a long period of time, a percentage of website surfers prefer to turn javascript functionality off on their browser rendering the AJAX application useless, a work around to this con is present as well, where the developer will need to code a parallel non-javascript version of the dynamic web page to cater to these users.

Difference between a CustomControl and a UserControl

Custom Control User Control
A loosely coupled control w.r.t code and UI A tightly coupled control w.r.t code and UI
Derives from Control Derives from UserControl
Defines UI in a ResourceDictionary Defines UI as normal XAML
UI is skinable Child controls are skinable
Has dynamic layout Has static layout
UI can be changed in different projects UI is fixed and can't have different looks in different project
Has full toolbox support Can't be added to the toolbox
Defines a single control Defines a set of controls
More flexible Not very flexible like a Custom Control
Requires in-depth knowledge of Silverlight UI Model Does not require indepth knowledge of the UI Model


  1. User Control is a page file with extension .ascx which can only be used within a single application. But custom controls are assemblies(dll files) that can be used in multiple applications.
  2. User Controls cannot be added to the ToolBox of VS.NET . To use a User Control with in an aspx page you have to drag the user Control from the solution explorer to designer page. But Custom Controls can be added to ToolBox of VS.NET.
  3. User Controls can be viewed as a sort of generic controls during the design time. The proper GUI of user controls can be viewed only during the run time. But Custom Controls can be viewed during the design time.
  4. User controls are created from existing Webserver and html server controls. But a developer who creates custom controls have to render every thing from the scratch.
  5. Since the dll assembly of a custom control is being used,a custom control developed in C# can be used in a project developed in VB.NET or any other managed code and vice versa. This is not possible with user controls.They are language specific

What is a User Control?

The base "UserControl" is nothing but a Custom Control that you derive to create a control UI specific to your project. Generally, we create a UserControl which is placed inside a ASPX page with tight bonding to the code behind. You can directly access its UI elements from the code-behind and do some specific operations.

A custom UserControl inherits from the System.Windows.Controls.UserControls class, which inherits from the base "Control" class.

You can't create theming support for UserControls but can style them by creating themes for the child Custom Controls because they represent a collection of controls. Once you create a UserControl UI in one project, you can't change it in other projects.

What is a Custom Control?

A custom control is a loosely coupled control defined in a class, which derives from Control. The UI of the custom control is generally defined in a Resource Dictionary inside the resource file. We can create themes for a custom control and reuse it in various projects very easily.
Button, CheckBox, TextBox etc., even a UserControl is nothing but a Custom Control. You can easily load them inside a ASPX page.

A Custom Control generally inherits from the System.Windows.Controls.Control class. You may derive from a different custom control depending on your requirement.

Custom Controls are compiled into a DLL assembly and can be reused in multiple places very easily. You have total control over the code, thus gives you more flexibility to extend the behaviour. Once you build and add a reference of the custom control in your project, you can find it in the toolbox. Thus, you will be able to drag and drop the control in your Design view and start working with it very easily.

Wednesday, August 13, 2014

Why layer a service?

An important aspect of SOA design is that service boundaries should be explicit, which means hiding all the details of the implementation behind the service boundary. This includes revealing or dictating what particular technology was used.
Furthermore, inside the implementation of a service, the code responsible for the data manipulation should be separated from the code responsible for the business logic. So in the real world, it is always good practice to implement a WCF service in three or more layers. The three layers are the service interface layer, the business logic layer, and the data access layer.

  • Service interface layer: This layer will include the service contracts and operation contracts that are used to define the service interfaces that will be exposed at the service boundary. Data contracts are also defined to pass in and out of the service. If any exception is expected to be thrown outside of the service, then Fault contracts will also be defined at this layer.
  • Business logic layer: This layer will apply the actual business logic to the service operations. It will check the preconditions of each operation, perform business activities, and return any necessary results to the caller of the service.
  • Data access layer: This layer will take care of all of the tasks needed to access the underlying databases. It will use a specific data adapter to query and update the databases. This layer will handle connections to databases, transaction processing, and concurrency controlling. Neither the service interface layer nor the business logic layer needs to worry about these things.

  • Layering provides separation of concerns and better factoring of code, which gives you better maintainability and the ability to split out layers into separate physical tiers for scalability. The data access code should be separated into its own layer that focuses on performing translation services between the databases and the application domain. Services should be placed in a separate service layer that focuses on performing translation services between the service-oriented external world and the application domain.

    The service interface layer will be compiled into a separate class assembly and hosted in a service host environment. The outside world will only know about and have access to this layer. Whenever a request is received by the service interface layer, the request will be dispatched to the business logic layer, and the business logic layer will get the actual work done. If any database support is needed by the business logic layer, it will always go through the data access layer.

    What is WCF?

    Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

    WCF makes the development of endpoints easier.It is designed to offer a manageable approach to creating Web services and Web service clients.


    WCF includes the following set of features.
    • Service Orientation
      One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met.
    • Interoperability
      WCF implements modern industry standards for Web service interoperability.
    • Multiple Message Patterns
      Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program.
    • Service Metadata
      WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard.
    • Data Contracts
      Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed.
    • Security
      Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation.
    • Multiple Transports and Encodings
      Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the HyperText Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding.
    • Reliable and Queued Messages
      WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ.
    • Durable Messages
      A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF).
    • Transactions
      WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System.Transactions namespace, and Microsoft Distributed Transaction Coordinator.
    • AJAX and REST Support
      REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON).
    • Extensibility
      The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service.

    Wednesday, August 6, 2014

    Dependency Injection

    Now that we know the dependency inversion principle and have seen the inversion of control methodology for implementing the dependency inversion principle, Dependency Injection is mainly for injecting the concrete implementation into a class that is using abstraction i.e. interface inside. The main idea of dependency injection is to reduce the coupling between classes and move the binding of abstraction and concrete implementation out of the dependent class.
    Dependency injection can be done in three ways.
    1. Constructor injection
    2. Method injection
    3. Property injection

    Constructor Injection 


    In this approach we pass the object of the concrete class into the constructor of the dependent class. So what we need to do to implement this is to have a constructor in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        public AppPoolWatcher(INofificationAction concreteImplementation)
        {
            this.action = concreteImplementation;
        }
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {   
            action.ActOnNotification(message);
        }
    }
    
    In the above code, the constructor will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher(writer);
    watcher.Notify("Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's constructor. This method is useful when we know that the instance of the dependent class will use the same concrete class for its entire lifetime.

    Method Injection


    In constructor injection we saw that the dependent class will use the same concrete class for its entire lifetime. Now if we need to pass separate concrete class on each invocation of the method, we have to pass the dependency in the method only.

    So in method injection approach we pass the object of the concrete class into the method the dependent class which is actually invoking the action. So what we need to do to implement this is to have the action function also accept an argument for the concrete class object and assign it to the interface handle this class is using and invoke the action. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(INofificationAction concreteAction, string message)
        {
            this.action = concreteAction;
            action.ActOnNotification(message);
        }
    }
    
    In the above code the action method i.e. Notify will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher();
    watcher.Notify(writer, "Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's invocation method i.e. Notify method in the above example. 

    Property Injection


    Now we have discussed two scenarios where in constructor injection we knew that the dependent class will use one concrete class for the entire lifetime. The second approach is to use the method injection where we can pass the concrete class object in the action method itself. But what if the responsibility of selection of concrete class and invocation of method are in separate places. In such cases we need property injection.

    So in this approach we pass the object of the concrete class via a setter property that was exposed by the dependent class. So what we need to do to implement this is to have a Setter property or function in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        public INofificationAction Action
        {
            get
            {
                return action;
            }
            set
            {
                action = value;
            }
        }
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {   
            action.ActOnNotification(message);
        }
    }
    
    In the above code the setter of Action property will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher();
    // This can be done in some class
    watcher.Action = writer;
    
    // This can be done in some other class
    watcher.Notify("Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the setter exposed by AppPoolWatcher class. This approach is useful when the responsibility of selecting the concrete implementation and invoking the action are done in separate places/modules. 

    In languages where properties are not supported, there is a separate function to set the dependency. This approach is also known as setter injection. The important thing to note in this approach is that there is a possibility that someone has created the dependent class but no one has set the concrete class dependency yet. If we try to invoke the action in such cases then we should have either some default dependency mapped to the dependent class or have some mechanism to ensure that application will behave properly.

    A Note on IoC Containers


    Constructor injection is the mostly used approach when it comes to implementing the dependency injection. If we need to pass different dependencies on every method call then we use method injection. Property injection is used less frequently.

    All the three approaches we have discussed for dependency injection are ok if we have only one level of dependency. But what if the concrete classes are also dependent of some other abstractions. So if we have chained and nested dependencies, implementing dependency injection will become quite complicated. That is where we can use IoC containers. IoC containers will help us to map the dependencies easily when we have chained or nested dependencies.


    What is Inversion of Control?

    Dependency inversion was a software design principle, it just states that how two modules should depend on each other. Now the question comes, how exactly we are going to do it? The answer is Inversion of control. Inversion of control is the actual mechanism using which we can make the higher level modules to depend on abstractions rather than concrete implementation of lower level modules.
    So if I have to implement inversion of control in the above mentioned problem scenario, the first thing we need to do is to create an abstraction that the higher levels will depend on. So let us create an interface that will provide the abstraction to act on the notification received from AppPoolWacther.

    public interface INofificationAction
    {
        public void ActOnNotification(string message);
    }
    
    
    Now let us change our higher level module i.e. the AppPoolWatcher to use this abstraction rather than the lower level concrete class.
    
    
    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {
            if (action == null)
            {
                // Here we will map the abstraction i.e. interface to concrete class 
            }
            action.ActOnNotification(message);
        }
    }
    
    So how will our lower level concrete class will change? how will this class conform to the abstraction i.e. we need to implement the above interface in this class:
     
    class EventLogWriter : INofificationAction
    {   
        public void ActOnNotification(string message)
        {
            // Write to event log here
        }
    }

    So now if I need to have the concrete classes for sending email and sms, these classes will also implement the same interface.

    class EmailSender : INofificationAction
    {
        public void ActOnNotification(string message)
        {
            // Send email from here
        }
    }
    
    class SMSSender : INofificationAction
    {
        public void ActOnNotification(string message)
        {
            // Send SMS from here
        }
    }
    
    So the final class design will look like: 


    So what we have done here is that, we have inverted the control to conform to dependency inversion principle. Now our high level modules are dependent only on abstractions and not the lower level concrete implementations, which is exactly what dependency inversion principle states.
    But there is still one missing piece. When we look at the code of our AppPoolWatcher, we can see that it is using the abstraction i.e. interface but where exactly are we creating the concrete type and assigning it to this abstraction. To solve this problem, we can do something like:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {
            if (action == null)
            {
                // Here we will map the abstraction i.e. interface to concrete class 
                writer = new EventLogWriter();
            }
            action.ActOnNotification(message);
        }
    }
    
    But we are again back to where we have started. The concrete class creation is still inside the higher level class. Can we not make it totally decoupled so that even if we add new classes derived from INotificationAction, we don't have to change this class. 

    This is exactly where Dependency injection comes in picture. So its time to look at dependency injection in detail now.