-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathStructureMapServiceProvider.cs
More file actions
59 lines (51 loc) · 1.69 KB
/
StructureMapServiceProvider.cs
File metadata and controls
59 lines (51 loc) · 1.69 KB
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
55
56
57
58
59
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
namespace StructureMap
{
public sealed class StructureMapServiceProvider : IServiceProvider, ISupportRequiredService
{
private readonly Stack<IContainer> _containers = new Stack<IContainer>();
public StructureMapServiceProvider(IContainer container)
{
if (container == null) throw new ArgumentNullException(nameof(container));
_containers.Push(container);
}
public IContainer Container => _containers.Peek();
public object GetService(Type serviceType)
{
// TryGetInstance doesn't resolve instances of concrete types
try
{
return Container.GetInstance(serviceType);
}
catch (StructureMapConfigurationException)
{
return null;
}
}
public object GetRequiredService(Type serviceType)
{
return Container.GetInstance(serviceType);
}
/// <summary>
/// Creates a new StructureMap child container and makes that the new active container
/// </summary>
public void StartNewScope()
{
var child = Container.CreateChildContainer();
_containers.Push(child);
}
/// <summary>
/// Tears down any active child container and pops it out of the active container stack
/// </summary>
public void TeardownScope()
{
if (_containers.Count >= 2)
{
var child = _containers.Pop();
child.Dispose();
}
}
}
}