This example demonstrates how Unity Container could be used with ASP.NET web applications. In order to enable Unity as default dependency injection provider you need to follow two simple steps:
- Reference the
Unity.Microsoft.DependencyInjectionpackage from NuGet.
Install-Package Unity.Microsoft.DependencyInjection
- In the
CreateHostBuilderaddUseUnityServiceProvider(...)method
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseUnityServiceProvider(...) <------ Add this line, you could pass IUnityContainer instance
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});Unity allows several scenarios how it could be used:
- Direct replancement of native DI
- Instance of Unity is created and configured manually
- Instance of Unity is created manually and configured from configuration file
- If you want you could add method to your
Startupclass
public void ConfigureContainer(IUnityContainer container)
{
// Could be used to register more types
container.RegisterType<IMyService, MyService>();
}By default ASP resolves controllers using built in activator. To enable resolution of controllers from Unity you need to add following line to MVC configuration:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllersAsServices(); <-- Add this line
...
}