Unity extension to integrate with Microsoft.Extensions.DependencyInjection compliant systems
- Reference the
Unity.Microsoft.DependencyInjection
package from NuGet.
Install-Package Unity.Microsoft.DependencyInjection
- In the
WebHostBuilder
addUseUnityServiceProvider(...)
method
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUnityServiceProvider() <---- Add this line
.UseStartup<Startup>()
.Build();
- In case Unity container configured via application configuration or by convention this container could be used to initialize service provider.
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUnityServiceProvider(_container) <---- or add this line
.UseStartup<Startup>()
.Build();
- Add optional method to your
Startup
class
public void ConfigureContainer(IUnityContainer container)
{
// Could be used to register more types
container.RegisterType<IMyService, MyService>();
}
Startup class instance is resolved from Unity if it is configured as default container.
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.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_xxx)
.AddControllersAsServices(); <-- Add this line
}
For example of using Unity with Core 2.0 Web application follow this link