How Dependency Injection Containers Work in C#?

Dependency Injection (DI) containers, such as Unity or DryIoc, help manage the creation and lifetime of object dependencies in C#. They facilitate the Inversion of Control (IoC) principle, allowing you to focus on writing clean, maintainable code without worrying about the complexities of instantiating dependencies manually. How DI Containers Work? Registration:  You define which concrete classes should be used to fulfill specific interface contracts. This allows the DI container to know what to instantiate when a class requests a particular dependency. Resolution:  When an instance of a class is requested, the DI container looks at the registered services, resolves the dependencies, and creates the object with the required dependencies injected. Lifetime Management:  The container manages the lifecycle of the dependencies. You can specify whether instances should be singleton (one instance for the entire application), transient (a new instance each time), or scoped (one ...

Step by step guide to implement the command in wpf

To create the custom command we need to implement ICommand interface which is having two method called CanExecute and Execute and one EventHandler called CanExecuteChanged.

  1. CanExecute method is responsible to tell if commend will execute or not.
  2. Execute method perform the action.
Step to create custom command:
  1. Implement the ICommand
  2. write a constructor which will take two parameters of type Action and Func respectively.
  3. if you want to trigger CanExecute on property change then add the method which should invoke CanExecuteChanged  EventHandler .
Why Action?

Action delegate is used for performing the action. As our actual implementation of  this Action will present in our ViewModel and we need to pass ViewModel method as a constructor parameter so that we can assign it in our CustomCommand and can invoke when require.

Why Func?

Func delegate is used when we want to pass some value and return some value. As our actual implementation of  this Func will present in our ViewModel and we need to pass ViewModel method as a constructor parameter so that we can assign it in our CustomCommand and can invoke when require.

public class CustomCommand : ICommand

    {

        public CustomCommand(Action<object> execute, Func<object, bool> canExecute)

        {

            this.execute = execute;

            this.canExecute = canExecute;

        }

        Action<object> execute;

        Func<object, bool> canExecute;

        public event EventHandler CanExecuteChanged;

        public void FireCanExecuteChanged()

        {

            CanExecuteChanged?.Invoke(this, EventArgs.Empty);

        }


        public bool CanExecute(object parameter)

        {

            return canExecute != null && canExecute(parameter);

        }


        public void Execute(object parameter)

        {

            execute?.Invoke(parameter);

        }

    }


How to use this Command in our ViewModel?

public CustomCommand ClickCommand { get; set; }

inside the ViewModel constructor we can instantiate the ClickCommand.


Lets take one example where we have one Textbox, one TextBlock and one Button control.

Now i want to Enable/Disable the button based on Textbox Property.


 <StackPanel>

        <TextBox Text="{Binding Message,UpdateSourceTrigger=PropertyChanged}"/>

        <Button Content="Click" Command="{Binding ClickCommand}"/>

        <TextBlock Text="{Binding MessageText}"/>

  </StackPanel>


ViewModel

public class MainWindowViewModel : INotifyPropertyChanged

    {

        public MainWindowViewModel()

        {

            ClickCommand = new CustomCommand(Execute,CanExecute);

        }


        private bool CanExecute(object arg)

        {

            return !string.IsNullOrEmpty(Message);

        }


        private void Execute(object obj)

        {

            MessageText = "Your text is : " + Message;

        }


        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChnaged(string propertyName)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        }

        private string _message;


        public string Message

        {

            get { return _message; }

            set

            {

                _message = value;

                OnPropertyChnaged(nameof(Message));

//we have to call this because if the property will change CanExecute will not execute and our Button

//Enable/Disable will not happen

                ClickCommand.FireCanExecuteChanged();

            }

        }

        private string _messageText;


        public string MessageText

        {

            get { return _messageText; }

            set

            {

                _messageText = value;

                OnPropertyChnaged(nameof(MessageText));

            }

        }

       public CustomCommand ClickCommand { get; set; }

    }


I hope this will help you.

                                                                                                            Happy Coding!!!

Comments

Popular posts from this blog

Filter DataGrid and ListView in wpf using ICollectionView

Pagination of DataGrid in WPF using MVVM

How to Create TabControl using Prism Region