forked from postsharp/PostSharp.Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
98 lines (81 loc) · 2.38 KB
/
Program.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
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using PostSharp.Serialization;
namespace PostSharp.Samples.DependencyResolution.Dynamic
{
public interface ILogger
{
void Log(string message);
}
public static class AspectServiceLocator
{
private static CompositionContainer container;
private static bool isCacheable;
public static void Initialize(ComposablePartCatalog catalog, bool isCacheable)
{
if (AspectServiceLocator.isCacheable && container != null)
throw new InvalidOperationException();
container = new CompositionContainer(catalog);
AspectServiceLocator.isCacheable = isCacheable;
}
public static Func<T> GetService<T>() where T : class
{
if (isCacheable)
{
return () => new Lazy<T>(GetServiceImpl<T>).Value;
}
else
{
return GetServiceImpl<T>;
}
}
private static T GetServiceImpl<T>()
{
if (container == null)
throw new InvalidOperationException();
return container.GetExport<T>().Value;
}
}
[PSerializable]
public class LogAspect : OnMethodBoundaryAspect
{
private static readonly Func<ILogger> logger;
static LogAspect()
{
if (!PostSharpEnvironment.IsPostSharpRunning)
{
logger = AspectServiceLocator.GetService<ILogger>();
}
}
public override void OnEntry(MethodExecutionArgs args)
{
logger().Log("OnEntry");
}
}
internal class Program
{
private static void Main(string[] args)
{
AspectServiceLocator.Initialize(new TypeCatalog(typeof(ConsoleLogger)), true);
LoggedMethod();
Console.ReadLine();
}
[LogAspect]
public static void LoggedMethod()
{
Console.WriteLine("Hello, world.");
}
}
[Export(typeof(ILogger))]
internal class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
}