-
Notifications
You must be signed in to change notification settings - Fork 122
/
CreateConcreteTask.cs
87 lines (69 loc) · 2.9 KB
/
CreateConcreteTask.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
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Castle.DynamicProxy;
using Glass.Mapper.Caching;
using Glass.Mapper.Profilers;
namespace Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateConcrete
{
public class CreateConcreteTask : ObjectConstructionTask
{
private const string ConstructorErrorMessage = "No constructor for class {0} with parameters {1}";
private static volatile ProxyGenerator _generator;
private static volatile ProxyGenerationOptions _options;
static CreateConcreteTask()
{
_generator = new ProxyGenerator();
var hook = new LazyObjectProxyHook();
_options = new ProxyGenerationOptions(hook);
}
public override void Execute(ObjectConstructionArgs args)
{
if (args.Result != null)
return;
var type = args.Configuration.Type;
if(type.IsInterface)
{
return;
}
if(args.AbstractTypeCreationContext.IsLazy)
{
//here we create a lazy loaded version of the class
args.Result = CreateLazyObject(args);
args.ObjectOrigin = ObjectOrigin.CreateConcreteLazy;
}
else
{
//here we create a concrete version of the class
args.Result = CreateObject(args);
args.ObjectOrigin = ObjectOrigin.CreateConcrete;
}
if (CacheDisabler.CacheDisabled || args.Context.ObjectCacheConfiguration == null)
{
args.AbortPipeline();
}
}
protected virtual object CreateLazyObject(ObjectConstructionArgs args)
{
return _generator.CreateClassProxy(args.Configuration.Type, new LazyObjectInterceptor(args));
}
protected virtual object CreateObject(ObjectConstructionArgs args)
{
var constructorParameters = args.AbstractTypeCreationContext.ConstructorParameters;
var parameters =
constructorParameters == null || !constructorParameters.Any() ? Type.EmptyTypes : constructorParameters.Select(x => x.GetType()).ToArray();
var constructorInfo = args.Configuration.Type.GetConstructor(parameters);
Delegate conMethod = args.Configuration.ConstructorMethods[constructorInfo];
var obj = conMethod.DynamicInvoke(constructorParameters);
//create properties
AbstractDataMappingContext dataMappingContext = args.Service.CreateDataMappingContext(args.AbstractTypeCreationContext, obj);
foreach (var prop in args.Configuration.Properties)
{
prop.Mapper.MapCmsToProperty(dataMappingContext);
}
return obj;
}
}
}