在应对这个挑战时,我的方法是通过查阅大量的参考文献来了解Roslyn可用的不同类型。
为了给最终解决方案加上前缀,让我们创建模块接口,并将其放在Contracts.dll
中:
public interface IModule
{
public int Order { get; }
public string Name { get; }
public Version Version { get; }
IEnumerable<ServiceDescriptor> GetServices();
}
public interface IModuleProvider
{
IEnumerable<IModule> GetModules();
}
同时,让我们定义出基本的提供者:
public abstract class ModuleProviderBase
{
private readonly List<IModule> _modules = new List<IModule>();
protected ModuleProviderBase()
{
Setup();
}
public IEnumerable<IModule> GetModules()
{
return _modules.OrderBy(m => m.Order);
}
protected void AddModule<T>() where T : IModule, new()
{
var module = new T();
_modules.Add(module);
}
protected virtual void Setup() { }
}
在这种架构中,模块实际上只是一个描述符,因此不应该具有依赖项,它仅表达了它提供的服务。
现在,以 DefaultLogger.dll
为例,一个模块可能看起来像:
public class DefaultLoggerModule : ModuleBase
{
public override int Order { get { return ModuleOrder.Level3; } }
public override IEnumerable<ServiceDescriptor> GetServices()
{
yield return ServiceDescriptor.Instance<ILoggerFactory>(new DefaultLoggerFactory());
}
}
为了简洁起见,我省略了ModuleBase
的实现。
现在,在我的Web项目中,我添加了对Contracts.dll
和DefaultLogger.dll
的引用,然后添加了以下模块提供程序的实现:
public partial class ModuleProvider : ModuleProviderBase { }
现在,我的ICompileModule
:
using T = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree;
using F = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using K = Microsoft.CodeAnalysis.CSharp.SyntaxKind;
public class DiscoverModulesCompileModule : ICompileModule
{
private static MethodInfo GetMetadataMethodInfo = typeof(PortableExecutableReference)
.GetMethod("GetMetadata", BindingFlags.NonPublic | BindingFlags.Instance);
private static FieldInfo CachedSymbolsFieldInfo = typeof(AssemblyMetadata)
.GetField("CachedSymbols", BindingFlags.NonPublic | BindingFlags.Instance);
private ConcurrentDictionary<MetadataReference, string[]> _cache
= new ConcurrentDictionary<MetadataReference, string[]>();
public void AfterCompile(IAfterCompileContext context) { }
public void BeforeCompile(IBeforeCompileContext context)
{
string ns = GetModuleProviderNamespace(context.Compilation.SyntaxTrees);
var modules = GetAvailableModules(context.Compilation).ToList();
var statements = modules.Select(m => F.ParseStatement("AddModule<" + module + ">();")).ToList();
var cu = F.CompilationUnit()
.AddMembers(
F.NamespaceDeclaration(F.IdentifierName(ns))
.AddMembers(
F.ClassDeclaration("ModuleProvider")
.WithModifiers(F.TokenList(F.Token(K.PartialKeyword)))
.AddMembers(
F.MethodDeclaration(F.PredefinedType(F.Token(K.VoidKeyword)), "Setup")
.WithModifiers(
F.TokenList(
F.Token(K.ProtectedKeyword),
F.Token(K.OverrideKeyword)))
.WithBody(F.Block(statements))
)
)
)
.NormalizeWhitespace(indentation("\t"));
var tree = T.Create(cu);
context.Compilation = context.Compilation.AddSyntaxTrees(tree);
}
}
本模块实际上包含以下几个步骤:
1 - 解析Web项目中ModuleProvider
实例的命名空间,例如:SampleWeb
。
2 - 通过引用发现所有可用的模块,并将它们作为字符串集合返回,例如:new[] { "SampleLogger.DefaultLoggerModule" }。
3 - 将它们转换为AddModule<SampleLogger.DefaultLoggerModule>();
这种类型的语句。
4 - 创建一个partial
实现的ModuleProvider
,并将其添加到我们的编译中:
namespace SampleWeb
{
partial class ModuleProvider
{
protected override void Setup()
{
AddModule<SampleLogger.DefaultLoggerModule>();
}
}
}
那么,我是如何发现可用的模块的呢?有三个阶段:
1 - 引用的程序集(例如通过NuGet提供的)
2 - 引用的编译(例如解决方案中引用的项目)。
3 - 当前编译中的模块声明。
对于每个引用的编译,我们重复上述步骤。
private IEnumerable<string> GetAvailableModules(Compilation compilation)
{
var list = new List<string>();
string[] modules = null;
var refs = compilation.References.ToList();
var assemblies = refs.OfType<PortableExecutableReference>().ToList();
foreach (var assemblyRef in assemblies)
{
if (!_cache.TryGetValue(assemblyRef, out modules))
{
modules = GetAssemblyModules(assemblyRef);
_cache.AddOrUpdate(assemblyRef, modules, (k, v) => modules);
list.AddRange(modules);
}
else
{
}
}
var compilations = refs.OfType<CompilationReference>().ToList();
foreach (var compliationRef in compilations)
{
if (!_cache.TryGetValue(compilationRef, out modules))
{
modules = GetAvailableModules(compilationRef.Compilation).ToArray();
_cache.AddOrUpdate(compilationRef, modules, (k, v) => modules);
list.AddRange(modules);
}
else
{
}
}
list.AddRange(GetModuleClassDeclarations(compilation));
return list;
}
因此,要获取已引用的程序集模块:
private IEnumerable<string> GetAssemblyModules(PortableExecutableReference reference)
{
var metadata = GetMetadataMethodInfo.Invoke(reference, nul) as AssemblyMetadata;
if (metadata != null)
{
var assemblySymbol = ((IEnumerable<IAssemblySymbol>)CachedSymbolsFieldInfo.GetValue(metadata)).First();
if (assemblySymbol.Name.StartsWith("Sample"))
{
var types = GetTypeSymbols(assemblySymbol.GlobalNamespace).Where(t => Filter(t));
return types.Select(t => GetFullMetadataName(t)).ToArray();
}
}
return Enumerable.Empty<string>();
}
我们需要进行一些反射处理,因为
GetMetadata
方法不是公共的,在获取元数据时,
CachedSymbols
字段也是非公共的,所以我们还需要进行更多的反射处理。在确定可用内容方面,我们需要从
CachedSymbols
属性中获取
IEnumerable<IAssemblySymbol>
。这将为我们提供参考程序集中所有缓存的符号。Roslyn已经为我们完成了这个操作,所以我们可以滥用它:
private IEnumerable<ITypeSymbol> GetTypeSymbols(INamespaceSymbol ns)
{
foreach (var typeSymbols in ns.GetTypeMembers().Where(t => !t.Name.StartsWith("<")))
{
yield return typeSymbol;
}
foreach (var namespaceSymbol in ns.GetNamespaceMembers())
{
foreach (var typeSymbol in GetTypeSymbols(ns))
{
yield return typeSymbol;
}
}
}
GetTypeSymbols
方法遍历命名空间并发现所有类型。然后将结果链接到过滤器方法,该方法确保其实现了我们所需的接口:
private bool Filter(ITypeSymbol symbol)
{
return symbol.IsReferenceType
&& !symbol.IsAbstract
&& !symbol.IsAnonymousType
&& symbol.AllInterfaces.Any(i => i.GetFullMetadataName(i) == "Sample.IModule");
}
使用 GetFullMetadataName
作为一个实用方法:
private static string GetFullMetadataName(INamespaceOrTypeSymbol symbol)
{
ISymbol s = symbol;
var builder = new StringBuilder(s.MetadataName);
var last = s;
while (!!IsRootNamespace(s))
{
builder.Insert(0, '.');
builder.Insert(0, s.MetadataName);
s = s.ContainingSymbol;
}
return builder.ToString();
}
private static bool IsRootNamespace(ISymbol symbol)
{
return symbol is INamespaceSymbol && ((INamespaceSymbol)symbol).IsGlobalNamespace;
}
接下来,当前编译中的模块声明:
private IEnumerable<string> GetModuleClassDeclarations(Compilation compilation)
{
var trees = compilation.SyntaxTrees.ToArray();
var models = trees.Select(compilation.GetSemanticModel(t)).ToArray();
for (var i = 0; i < trees.Length; i++)
{
var tree = trees[i];
var model = models[i];
var types = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ToList();
foreach (var type in types)
{
var symbol = model.GetDeclaredSymbol(type) as ITypeSymbol;
if (symbol != null && Filter(symbol))
{
yield return GetFullMetadataName(symbol);
}
}
}
}
就是这样!所以,现在在编译时,我的ICompileModule
将会:
- 发现所有可用的模块
- 实现重载我的
ModuleProvider.Setup
方法,并加入所有已知的引用模块。
这意味着我可以在启动时添加:
public class Startup
{
public ModuleProvider ModuleProvider = new ModuleProvider();
public void ConfigureServices(IServiceCollection services)
{
var descriptors = ModuleProvider.GetModules()
.SelectMany(m => m.GetServices());
}
public void Configure(IApplicationBuilder app)
{
var modules = ModuleProvider.GetModules();
}
}
这个东西有点过度设计,比较复杂,但我认为还是很棒的!