-
Notifications
You must be signed in to change notification settings - Fork 3
/
MefDependencyResolver.cs
76 lines (67 loc) · 2.22 KB
/
MefDependencyResolver.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;
namespace Shop.WebApi
{
public class MefDependencyResolver : IDependencyResolver
{
private CompositionContainer container;
/// <summary>
/// Initializes a new instance of the <see cref="MefDependencyResolver"/> class.
/// </summary>
/// <param name="container">MEF composition container used for DI</param>
public MefDependencyResolver(CompositionContainer container)
{
this.container = container;
}
/// <summary>
/// Finalizer for <see cref="MefDependencyResolver"/>
/// </summary>
~MefDependencyResolver()
{
this.Dispose(false);
}
/// <inheritdoc />
public IDependencyScope BeginScope()
{
return new MefDependencyResolver(new CompositionContainer(this.container.Catalog, this.container));
}
/// <inheritdoc />
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing">Value indicating whether this method was explicitly called</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.container.Dispose();
GC.SuppressFinalize(this);
}
}
/// <inheritdoc />
public object GetService(Type serviceType)
{
var exports = this.container.GetExports(serviceType, null, null).FirstOrDefault();
return exports?.Value;
}
/// <inheritdoc />
public IEnumerable<object> GetServices(Type serviceType)
{
var exports = this.container.GetExports(serviceType, null, null);
var result = new List<object>(exports.Count());
foreach (var export in exports)
{
result.Add(export.Value);
}
return result;
}
}
}