-
Notifications
You must be signed in to change notification settings - Fork 218
/
CodeGeneratorDescriptor.cs
107 lines (92 loc) · 3.48 KB
/
CodeGeneratorDescriptor.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
99
100
101
102
103
104
105
106
107
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.Web.CodeGeneration.Core;
namespace Microsoft.VisualStudio.Web.CodeGeneration
{
public class CodeGeneratorDescriptor
{
private const string GenerateCodeMethodName = "GenerateCode";
private readonly TypeInfo _codeGeneratorType;
private readonly IServiceProvider _serviceProvider;
private ActionDescriptor _codeGeneratorAction;
public CodeGeneratorDescriptor(TypeInfo codeGeneratorType,
IServiceProvider serviceProvider)
{
if (codeGeneratorType == null)
{
throw new ArgumentNullException(nameof(codeGeneratorType));
}
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
_codeGeneratorType = codeGeneratorType;
_serviceProvider = serviceProvider;
}
public virtual string Name
{
get
{
var alias = _codeGeneratorType.GetAliasAttribute();
return alias != null ? alias.Alias : _codeGeneratorType.Name;
}
}
public virtual ActionDescriptor CodeGeneratorAction
{
get
{
if (_codeGeneratorAction == null)
{
var candidates = _codeGeneratorType
.GetDeclaredMethods(GenerateCodeMethodName)
.Where(mi => IsValidAction(mi));
var count = candidates.Count();
if (count == 0)
{
throw new InvalidOperationException(string.Format(MessageStrings.MethodNotFound , GenerateCodeMethodName, _codeGeneratorType.FullName));
}
if (count > 1)
{
throw new InvalidOperationException(string.Format(MessageStrings.MultipleMethodsFound, GenerateCodeMethodName, _codeGeneratorType.FullName));
}
_codeGeneratorAction = new ActionDescriptor(this, candidates.First());
}
return _codeGeneratorAction;
}
}
public virtual object CodeGeneratorInstance
{
get
{
object instance;
try
{
instance = ActivatorUtilities.CreateInstance(_serviceProvider, _codeGeneratorType.AsType());
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(MessageStrings.CodeGeneratorInstanceCreationError, _codeGeneratorType.FullName, ex.Message));
}
return instance;
}
}
private bool IsValidAction(MethodInfo method)
{
if (method.ContainsGenericParameters || method.IsAbstract || method.IsStatic)
{
return false;
}
var parameters = method.GetParameters();
if (parameters.Count() != 1)
{
return false;
}
//Should we validate the type of parameter?
return true;
}
}
}