StructureMap can inject the necessary dependencies seamlessly in your WebAPI controllers Credit: IDG Dependency injection enables you to inject dependencies in your application and in doing so, you can separate the implementation from the interface. In essence, dependency injection enables you to change the dependencies (the implementations) without having to change the types that need those dependencies. Here the term dependency implies a dependent object that needs one or more objects or dependencies for it to operate. In an earlier post here, I presented a discussion on how we can implement dependency injection using NInject. This time, we will explore another dependency injection framework named StructureMap. It should be noted that StructureMap is one of the popular and widely used Dependency Injection (DI) frameworks around. This article presents a discussion on how we can work with StructureMap to inject dependencies in WebAPI. Getting started using StructureMap To get started using StructureMap in WebAPI, you should first create a WebAPI application. To do this, follow these steps outlined below. Open Visual Studio IDE (I’m using VS.NET 2017, but you can also use any earlier version as well) Create a new WebAPI project Now install the necessary StructureMap package via NuGet Package Manager Once StructureMap has been successfully installed in your WebAPI project, you would observe that two files, namely Structuremap.Mvc.cs and Structuremap.WebApi.cs has beed addedd to the App_Start solution folder. And, another solution folder named DependencyResolution will be added with a list of files added to it. Implementing dependency injection In this section we will implement a simple application to demonstrate how we can work with StructureMap. Consider the following types — the IProductRepository interface and the ProductRepository class. The ProductRepository class implements the IProductRepository interface. Note that I have provided the structure of the class — you can write the necessary implementation as needed. public interface IProductRepository { IEnumerable<Product> GetAll(); Product Get(int id); } public class ProductRepository : IProductRepository { public IEnumerable<Product> GetAll() { //Write your implementation here return null; } public Product Get(int id) { //Write your implementation here return null; } } The ProductsController uses the ProductRepository class to retrieve data as shown below. public class ProductsController : ApiController { private IProductRepository _repository; public ProductsController(IProductRepository repository) { _repository = repository; } public IHttpActionResult GetAll() { var products = _repository.GetAll(); return Ok(products); } public IHttpActionResult GetByID(int id) { var product = _repository.Get(id); if (product == null) { return NotFound(); } return Ok(product); } } As you can see in the ProductController class given above, a reference to the repository interface, i.e., the IProductRepository interface is available. This would ensure that if the implementation of the ProductRepository changes, the types that depend on the implementation, i.e., the ProductsController would not be affected. The next thing that you should do is register the ProductRepository with the Dependency Injection container. To do this, you should specify the following statement in the DefaultRegistry.cs file present inside the DependencyResolution folder. For<IProductRepository>().Use<ProductRepository>(); The DefaultRegistry class would now look like this. public class DefaultRegistry : Registry { #region Constructors and Destructors public DefaultRegistry() { Scan( scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); For<IProductRepository>().Use<ProductRepository>(); } Lastly, you should write the necessary code to start the DI container. To do this, specify the following statement in the Register method of the WebApiConfig.cs file. StructuremapWebApi.Start(); And that’s all you have to do. You can now test your application and setup breakpoints to see where and how the dependency is being injected at run time. Dependency injection helps you to build pluggable implementations in your application — it eliminates the hard-coded dependencies between the types and makes your types easier to build, test, and maintain over time. I will write more on DI containers in my future posts here. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos