簡體   English   中英

在注入到主程序集中的引用庫中獲取主程序集名稱

[英]Get main Assembly name in referenced library which is injected into main Assembly

我有MySolution.MyLibrary類庫,該類庫使用SimpleInjector在MySolution.MyService WCF服務中注冊:

container.Register<IMyLibrary, MyLibrary>(LifeStyle.Singleton);

我需要在MySolution.MyService的構造函數中MySolution.MyLibrary主程序集MySolution.MyServiceMySolution.MyLibrary 我已經嘗試過Assembly。*方法,但無法完成。 有什么想法我可以得到這個名字嗎?

這些是我嘗試過的:

Assembly.GetExecutingAssembly().GetName().FullName
"MySolution.MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

Assembly.GetCallingAssembly().GetName().FullName
"Anonymously Hosted DynamicMethods Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"

Assembly.GetEntryAssembly()
null 
using System.Diagnostics;
using System.Linq;

...

StackFrame[] frames = new StackTrace().GetFrames();
string initialAssembly = (from f in frames 
                          select f.GetMethod().ReflectedType.AssemblyQualifiedName
                         ).Distinct().Last();

檢查這個問題

更新

將以下代碼用於WCF:

var currentAssembly = Assembly.GetExecutingAssembly();
        var callerAssemblies = new StackTrace().GetFrames()
            .Where(x => x.GetMethod() != null && x.GetMethod().ReflectedType != null )
                    .Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
                    .Where(x => x.GetReferencedAssemblies().Any(y => y.FullName == currentAssembly.FullName));
        var initialAssembly1 = callerAssemblies.Last();

在此處輸入圖片說明

您可以簡單地注入以下信息:

public class MyLibrary : IMyLibrary
{
    public MyLibrary(string assemblyName) { ... }
}

通過如下注冊:

container.RegisterSingleton<IMyLibrary>(new MyLibrary(
    Assembly.GetExecutingAssembly().GetName().FullName));

或者,如果您需要使用自動 MyLibrary (由於MyLibrary包含其他依賴項,請將配置值提取到配置對象中:

public class MyLibraryConfig
{
    public readonly string AssemblyName;

    public MyLibraryConfig(string assemblyName) { 
        this.AssemblyName = assemblyName;
    }
}

public class MyLibrary : IMyLibrary
{
    public MyLibrary(MyLibraryConfig config, IOtherDependency dep) { ... }
}

使用以下配置:

container.RegisterSingleton(new MyLibraryConfig(
    Assembly.GetExecutingAssembly().GetName().FullName));

container.Register<IMyLibrary, MyLibrary>(Lifestyle.Singleton)

嘗試類似:

MethodBase entryMethod = null;
var methodFrames = new StackTrace().GetFrames().Select(t => t.GetMethod()).ToList();
foreach (var method in methodFrames)
{
    if (method.Name == "Main" && method.ReturnType == typeof(void)){
        entryMethod = method;
    }
}
Assembly entryAssembly = entryMethod.Module.Assembly;

不過,還沒有進行測試,其想法是遍歷這些方法,直到您從庫中找到一個已知方法為止,例如該示例從控制台應用程序中查找Main方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM