Dependency Injection in .NET Core

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using DIExample.Models;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace DIExample.Controllers{[ApiController][Route(“[controller]”)]public class ProductController : ControllerBase{private readonly IProductDetails _productDetails;public ProductController(IProductDetails productDetails){_productDetails = productDetails;}public string Index(){return _productDetails.GetProduct();}}}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace DIExample.Models{public class ProductDetails : IProductDetails{public string GetProduct(){return “TestProduct”;}}}
namespace DIExample.Models{public interface IProductDetails{string GetProduct();}}
public void ConfigureServices(IServiceCollection services){services.AddControllers();services.AddSingleton<IProductDetails, ProductDetails>();}
  • Reduces class coupling
  • Increases code reusability
  • Improves code maintainability
  • Make unit testing possible

--

--

--

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to develop a cloud-based SaaS solution in 6 Steps

Mercury 110 98 Serial Number

Travis CI: Continuous Integration

Fuzzy.One — June 14 Update

What Is the JVM?

Snowflake: Select Show to JSON

The Power of SQL

AWS Invests New Region in Indonesia, So What’s Next ?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vaibhav Bhapkar

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

More from Medium

Unit Testing, a necessary evil?

Split your app into logical tires

The Application Diagram

How to write a unit test for your custom attribute which extends ActionFilterAttribute in c# .net

What is Multithreading? Pros and Cons.