【问题标题】:Use Microsoft.AspNetCore dll in text generation t4 file在文本生成 t4 文件中使用 Microsoft.AspNetCore dll
【发布时间】:2018-12-07 15:05:21
【问题描述】:

我正在尝试使用 t4 文件为我的 ASP.Core Web api 生成一些代码。我需要在.tt 文件中执行以下代码

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="Microsoft.AspNetCore.Mvc.ViewFeatures.dll" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Runtime" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
    <#
        // put cs code here 

        var asm = Assembly.LoadFrom(Path.Combine(Directory.GetCurrentDirectory(), "D:\\work\\AITeF\\AdministratorModule\\AdministratorModule\\bin\\Debug\\netcoreapp2.1\\AdministratorModule.dll"));

        var controlleractionlist = asm.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
            .Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
    #>

但是,我总是收到一个错误,即找不到命名空间“控制器”。我怎样才能引用这个.dll 来执行我的代码而不会出错。

【问题讨论】:

    标签: asp.net-mvc t4


    【解决方案1】:

    Microsoft.AspNetCore.Mvc.ViewFeatures.dll 添加有效路径后,您需要导入Controller 的命名空间或完全限定它

    <#@ assembly name="a:\valid\path\to\Microsoft.AspNetCore.Mvc.ViewFeatures.dll" #>
    <#@ assembly name="System.Core" #>
    // ...
    <#@ import namespace="Microsoft.AspNetCore.Mvc.Controller" #>
    
    // or fully qualified
        var controlleractionlist = asm.GetTypes()
            .Where(type => typeof(Microsoft.AspNetCore.Mvc.Controller).IsAssignableFrom(type))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多