PageRenderTime 214ms CodeModel.GetById 59ms app.highlight 4ms RepoModel.GetById 68ms app.codeStats 0ms

/src/LinFu.AOP/Factories/TypeWeaverActionFactory.cs

http://github.com/philiplaureano/LinFu
C# | 54 lines | 32 code | 7 blank | 15 comment | 1 complexity | 0e587cf0c0fd423aa20a8ba522e8239e MD5 | raw file
 1using System;
 2using LinFu.AOP.Cecil.Interfaces;
 3using LinFu.IoC.Configuration;
 4using LinFu.IoC.Interfaces;
 5using Mono.Cecil;
 6
 7namespace LinFu.AOP.Cecil.Factories
 8{
 9    /// <summary>
10    ///     Represents a class that generates <see cref="Action{T1,T2}" /> instances
11    ///     that apply a specific method weaver (with the name given in the first delegate parameter)
12    ///     to a specific <see cref="TypeDefinition" /> instance.
13    /// </summary>
14    [Factory(typeof(Action<string, TypeDefinition>), ServiceName = "TypeWeaver")]
15    public class TypeWeaverActionFactory : IFactory
16    {
17        /// <summary>
18        ///     Generates the <see cref="Action{T1, T2}" /> instance that will
19        ///     weave the target type.
20        /// </summary>
21        /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service request.</param>
22        /// <returns>The <see cref="Action{T1, T2}" /> instance that will weave the target type.</returns>
23        public object CreateInstance(IFactoryRequest request)
24        {
25            var container = request.Container;
26            Action<string, TypeDefinition> result =
27                (weaverName, type) =>
28                {
29                    // Get the method weaver instance that matches the weaverName
30                    var methodWeaver =
31                        (IHostWeaver<TypeDefinition>)
32                        container.GetService(weaverName, typeof(IHostWeaver<TypeDefinition>));
33
34                    // Wrap it in a type weaver
35                    var typeWeaver =
36                        (ITypeWeaver) container.GetService("AutoMethodWeaver", typeof(ITypeWeaver), methodWeaver);
37
38                    var module = type.Module;
39                    if (!typeWeaver.ShouldWeave(type))
40                        return;
41
42                    // Modify the host module
43                    typeWeaver.ImportReferences(module);
44                    typeWeaver.AddAdditionalMembers(module);
45
46                    // Weave the type itself
47                    typeWeaver.Weave(type);
48                };
49
50
51            return result;
52        }
53    }
54}