Using StructureMap with ASP.NET Core
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Introduction
This example shows how to use Structuremap dependency injection framework with ASP.NET Core instead of framework-level dependency injection. For framework level dependency injection example check out my tech.io playground Framework-level dependency injection with ASP.NET Core.
Adding StructureMap to ASP.NET Core project
For Structuremap support in ASP.NET Core application we need two NuGet packages:
- StructureMap - core StructureMap package
- StructureMap.Microsoft.DependencyInjection - adds support for ASP.NET Core
These packages are enough for getting StructureMap up and running.
Demo services
For demo purposes let's define primitive messaging service interface and couple of implementations.
public interface IMessagingService
{
string GetMessage();
}
public class BuiltInDiMessagingService : IMessagingService
{
public string GetMessage()
{
return "Hello from built-in dependency injection!";
}
}
public class StructuremapMessagingService : IMessagingService
{
public string GetMessage()
{
return "Hello from Structuremap!";
}
}
We need two implementations to demonstrate how built-in dependency injection is replaced by StructureMap.
Defining StructureMap registry
StructureMap uses registry classes for defining dependencies. Direct definitions are also supported but for more complex applications we will write registries anyway. Here is our registry class.
public class MyStructuremapRegistry : Registry
{
public MyStructuremapRegistry()
{
For<IMessagingService>().LifecycleIs(Lifecycles.Container)
.Use<StructuremapMessagingService>();
}
}
Attaching StructureMap to ASP.NET Core application
StructureMap is attached to ASP.NET Core when application is starting up. We have to make three updates to ConfigureServices() method of StartUp class:
- initialize and configure StructureMap container
- make ConfigureServices return IServiceProvider
- return IServiceProvider by StructureMap
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<IMessagingService, BuiltInDiMessagingService>();
var container = new Container();
container.Configure(config =>
{
config.AddRegistry(new MyStructuremapRegistry());
config.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
Notice that there is also dependecy definition for framework-level dependency injection. Let's see which implementation wins.
Trying out StructureMap with ASP.NET Core 2.0
Let's make some minor updates to Home controller and Index view to get message from injected service and display it on home page of sample application.
References
- Dependency injection in ASP.NET 5 (Gunnar Peipman)
- ASP.NET Core: Using third-party DI/IoC containers (Gunnar Peipman)