-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathFooBuildPlanCreatorPolicy.cs
49 lines (41 loc) · 1.66 KB
/
FooBuildPlanCreatorPolicy.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
using System.Linq;
using System.Reflection;
using Unity;
using Unity.Builder;
using Unity.Policy;
using Unity.Resolution;
namespace BuildPlanCreatorExample
{
public class FooBuildPlanCreatorPolicy
{
private readonly IPolicyList _policies;
private readonly MethodInfo _factoryMethod =
typeof(FooBuildPlanCreatorPolicy).GetTypeInfo().GetDeclaredMethod(nameof(FactoryMethod));
/// <summary>
/// Factory plan to build [I]Foo type
/// </summary>
/// <param name="policies">Container policy list to store created plans</param>
public FooBuildPlanCreatorPolicy(IPolicyList policies)
{
_policies = policies;
}
public ResolveDelegate<BuilderContext> GetResolver(ref BuilderContext context)
{
// Make generic factory method for the type
var typeToBuild = context.Type.GetTypeInfo().GenericTypeArguments.First();
var factoryMethod = (ResolveDelegate<BuilderContext>)
_factoryMethod.MakeGenericMethod(typeToBuild)
.CreateDelegate(typeof(ResolveDelegate<BuilderContext>));
// Register BuildPlan policy with the container to optimize performance
_policies.Set(context.Type, typeof(ResolveDelegate<BuilderContext>), factoryMethod);
return factoryMethod;
}
private static object FactoryMethod<TResult>(ref BuilderContext context)
{
// Resolve requested type
var service = (TResult)context.Resolve(typeof(TResult), context.Name);
// Create Foo
return new Foo<TResult>(service);
}
}
}