-
Notifications
You must be signed in to change notification settings - Fork 45
/
CustomServiceBasedControllerActivator.cs
54 lines (42 loc) · 1.83 KB
/
CustomServiceBasedControllerActivator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using BuildingBlocks.Abstractions.Web.Module;
using BuildingBlocks.Web.Module;
using Microsoft.AspNetCore.Mvc.Controllers;
namespace FoodDelivery.Api;
/// <summary>
/// This class will customize built-in <see cref="ServiceBasedControllerActivator"/> class.
/// Ref: https://andrewlock.net/controller-activation-and-dependency-injection-in-asp-net-core-mvc
/// </summary>
public class CustomServiceBasedControllerActivator : IControllerActivator
{
private IServiceScope _serviceScope;
public object Create(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var controllerAssembly = context.ActionDescriptor.ControllerTypeInfo.Assembly;
IModuleDefinition? selectedModuleToRoute = null;
foreach (var moduleDefinition in ModuleRegistry.ModuleDefinitions)
{
if (moduleDefinition.GetType().Assembly.GetName().Name == controllerAssembly.GetName().Name)
{
selectedModuleToRoute = moduleDefinition;
break;
}
}
if (selectedModuleToRoute is null)
throw new Exception("Appropriate module for routed controller not found!");
var compositionRoot = CompositionRootRegistry.GetByModule(selectedModuleToRoute);
if (compositionRoot is null)
{
throw new Exception(
$"Appropriate composition root for module `{selectedModuleToRoute.GetType().Name}` not found!");
}
_serviceScope = compositionRoot.ServiceProvider.CreateScope();
Type serviceType = context.ActionDescriptor.ControllerTypeInfo.AsType();
return _serviceScope.ServiceProvider.GetRequiredService(serviceType);
}
public void Release(ControllerContext context, object controller)
{
_serviceScope.Dispose();
}
}