How To Implement Di in Webapi Using Structuremap
How To Implement Di in Webapi Using Structuremap
How To Implement Di in Webapi Using Structuremap
using StructureMap
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.
1. Open Visual Studio IDE (I’m using VS.NET 2017, but you can also use any earlier version as well)
2. Create a new WebAPI project
3. 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.
IEnumerable<Product> GetAll();
{
public IEnumerable<Product> GetAll()
return null;
return null;
_repository = repository;
return Ok(products);
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>();
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.