繁体   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