|
| 1 | + |
| 2 | +# Example |
| 3 | +This example demonstrates how Unity Container could be used with ASP.NET web applications. |
| 4 | +In order to enable Unity as default dependency injection provider you need to follow two simple steps: |
| 5 | + |
| 6 | +## Install package |
| 7 | +- Reference the `Unity.Microsoft.DependencyInjection` package from NuGet. |
| 8 | +``` |
| 9 | +Install-Package Unity.Microsoft.DependencyInjection |
| 10 | +``` |
| 11 | + |
| 12 | +## Register Unity as default service provider |
| 13 | +- In the `CreateHostBuilder` add `UseUnityServiceProvider(...)` method |
| 14 | + |
| 15 | +```C# |
| 16 | +public static IHostBuilder CreateHostBuilder(string[] args) => |
| 17 | + Host.CreateDefaultBuilder(args) |
| 18 | + .UseUnityServiceProvider(...) <------ Add this line, you could pass IUnityContainer instrance |
| 19 | + .ConfigureWebHostDefaults(webBuilder => |
| 20 | + { |
| 21 | + webBuilder.UseStartup<Startup>(); |
| 22 | + }); |
| 23 | +``` |
| 24 | + |
| 25 | +## Using Unity |
| 26 | +Unity allows several scenarios how it could be used: |
| 27 | +- Direct replancement of native DI |
| 28 | +- Instance of Unity is created and configured manually |
| 29 | +- Instance of Unity is created manually and configured from configuration file |
| 30 | + |
| 31 | +### Startup |
| 32 | + |
| 33 | +Class `Startup` is now resolved from Unity container so if you registered any types it would be available during construction. |
| 34 | + |
| 35 | +- If you want you could add method to your `Startup` class |
| 36 | +```C# |
| 37 | +public void ConfigureContainer(IUnityContainer container) |
| 38 | +{ |
| 39 | + // Could be used to register more types |
| 40 | + container.RegisterType<IMyService, MyService>(); |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +### Resolving Controllers from Unity |
| 45 | + |
| 46 | +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: |
| 47 | +```C# |
| 48 | +public void ConfigureServices(IServiceCollection services) |
| 49 | +{ |
| 50 | + ... |
| 51 | + services.AddControllersAsServices(); <-- Add this line |
| 52 | + ... |
| 53 | +} |
| 54 | +``` |
| 55 | + |
0 commit comments