-
Notifications
You must be signed in to change notification settings - Fork 13
/
AutofacAopSample.cs
78 lines (66 loc) · 1.98 KB
/
AutofacAopSample.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
using System;
using System.Reflection;
using Autofac;
using Castle.DynamicProxy;
using Snap;
using Snap.Autofac;
namespace ConsoleApplication1
{
//
// NOTE: Use this sample as follows: SampleAutofacAopConfig.Intercept()
//
public static class SampleAutofacAopConfig
{
private readonly static ContainerBuilder _builder;
static SampleAutofacAopConfig()
{
_builder = new ContainerBuilder();
SnapConfiguration.For(new AutofacAspectContainer(_builder)).Configure(c =>
{
c.IncludeNamespace("ConsoleApplication1");
c.Bind<SampleInterceptor>().To<SampleAttribute>();
});
_builder.Register(r => new SampleClass()).As<ISampleClass>();
}
public static void Intercept()
{
using (var container = _builder.Build())
{
var instance = container.Resolve<ISampleClass>();
instance.Run();
}
}
}
public interface ISampleClass
{
void Run();
}
public class SampleClass : ISampleClass
{
[Sample] // Don't forget your attribute!
public void Run()
{
Console.WriteLine("inside the method");
}
}
public class SampleInterceptor : MethodInterceptor
{
public override void BeforeInvocation()
{
Console.WriteLine("this is executed before your method");
base.BeforeInvocation();
}
public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
{
// Just keep running for this demo.
invocation.Proceed(); // the underlying method call
}
public override void AfterInvocation()
{
Console.WriteLine("this is executed after your method");
base.AfterInvocation();
}
}
public class SampleAttribute : MethodInterceptAttribute
{ }
}