Dependency Injection Interview Questions – C#

If you are a software developer, you must not be alien to the dependency injection design pattern. Dependency injection (long form for DI) design pattern is broadly used in applications to manage dependencies for different components, especially in enterprise level applications. Dependency injection is so useful that even in front end frameworks, like Angular, provides inbuilt dependency injection feature.

If you have exposure to development in dot net framework, you might be aware that the new ASP.Net Core also supports inbuilt dependency injection feature.

The basic result that we attain through Dependency injection is that different components become independent of each other, i.e. loosely coupled.

Let us understand below what is dependency injection, why do we require it and the interview questions related to it.

What is Dependency Injection

Let’s understand what is dependency while developing applications. Suppose you have a service layer, business layer, and repository layer. The UI sends a request to the service, which invokes the business layer and which in turn invokes the repository layer to fetch the DB Data:

Now, there is a dependency of the repository layer on the business layer. Let’s look at the below code for this scenario:

    public class UserBusiness
    {
        private IRepository userRepo = new UserSQLRepository();
        public User GetUserData(int userId)
        {
            return userRepo.FetchUser(userId);
        }
    }

    interface IRepository
    {
        public User FetchUser(int userId);
    }

    public class UserSQLRepository: IRepository
    {
        public User FetchUser(int userId)
        {
            User user = new User();
            // DB call to fetch user Data on the basis of userId
            return user;
        }
    }

    public class User { }

The UserBusiness has now a dependency on IRepository to fetch the user data. Dependency injection makes these 2 classes as loosely coupled, i.e. to be independent of each other. The dependency injection framework helps handle all the changes required to initialize and provide the IRepository to the UserBusiness. It must not be the responsibility of the UserBusiness to initialize the IRepository.

Why do we need dependency injection

The question arises that why do we even need dependency injection in the first place. Let us understand why:

Imagine that in future the client needs to migrate the database from SQL to Oracle, now instead of the UserSQLRepository, the UserBusiness needs an object of UserOracleRepository. Although, it is simple to implement it here itself by just changing the initialization to UserSQLRepository to UserOracleRepository. If the application code base is big, one can use simple find and replace to change it.

Now, let’s say, the client wants the Database to be configurable, so we can create a configuration file and then in UserBusiness, we can simply call a factory class to initiate the repository object on the basis of configuration as below:

    public class UserBusiness
    {
        private IRepository userRepo = RepositoryFactory.Create();
        public User GetUserData(int userId)
        {
            return userRepo.FetchUser(userId);
        }
    }

Dependency injection framework inverts the control of the dependency initialization to the dependency injection framework. Instead of the various classes in the application , the Dependency injection framework works to resolve all of the dependencies.

How to implement Dependency injection in ASP.NET Core

The DI framework is inbuilt into the ASP.Net Core framework. Inside the middleware, on the configureservices method, the dependencies could be mentioned.

        private static IServiceCollection ConfigureServices()
        {
            IServiceCollection services = new ServiceCollection();

          
            services.AddTransient<IRepository, UserSQLRepository>();
            
            return services;

        }

How to implement Dependency injection in .NET Framework

Nuget Packages or libraries for Dependency injection implementation is required in Dot Net Framework. Microsoft provides “Microsoft unity framework” for the same. After installing the Nuget Package, a unity.config xml file generates. Interfaces to concreate implementation is mentioned in this file. A benefit for this is that the application need not recompile if we modify the configuration file.

What are scopes in dependency injection

Scope is the lifetime of the Object initialized through DI

There are 3 types of scopes:

  1. Singleton – There is a single object allocated for the whole application.
  2. Transient – A new object is initialized for every time a request is sent on the server.
  3. Scoped – A new object is allocated for each different API request. When API is hit for the first time, the objects are initialized through DI and then remains the same for that particular API.

What are the ways of implementing dependency injection

Constructor injection

The object is initialized in constructor by the DI framework.

    public class UserService
    {
        private IBusiness business;
        public UserService(IBusiness business)
        {
            this.business = business;
        }

        public User GetUserData(int userId)
        {
            return this.business.GetUserData(userId);
        }

    }

    public interface IBusiness
    {
        public User GetUserData(int userId);
    }

    public class UserBusiness : IBusiness
    {
        private IRepository userRepo;

        public UserBusiness(IRepository repo)
        {
            this.userRepo = repo;
        }

        public User GetUserData(int userId)
        {
            return userRepo.FetchUser(userId);
        }
    }

    public interface IRepository
    {
        public User FetchUser(int userId);
    }

    public class UserSQLRepository: IRepository
    {
        public User FetchUser(int userId)
        {
            User user = new User();
            // DB call to fetch user Data on the basis of userId
            return user;
        }
    }

Setter injection

The DI framework initializes the object using the setter of property.

    public class UserBusiness : IBusiness
    {
        private IRepository userRepo { get; set; }

        public User GetUserData(int userId)
        {
            return userRepo.FetchUser(userId);
        }
    }

Method Injection

The DI framework initializes the object in the method parameter.

Further benefits of using DI framework

  1. The Dependency injection framework helps in maintaining the code in a much better way.
  2. Dependency injection eases out writing unit test cases of the application, since we can simply inject a mock as dependency while testing.

Conclusion

Dependency Injection is a very useful framework for managing large scale applications and increases flexibility for modification in the application. Also, it is very useful for testing code using unit test cases.

Please let us know your suggestions in the comment box below.

Leave a Comment

Your email address will not be published.