I have MySolution.MyLibrary
class library which I register in MySolution.MyService
WCF service using SimpleInjector:
container.Register<IMyLibrary, MyLibrary>(LifeStyle.Singleton);
I need to get the name of the main assembly, MySolution.MyService
, in the constructor of MySolution.MyLibrary
. I've tried Assembly.* methods but I couldn't manage to do it. Any ideas how I can get the name?
These are what I've tried:
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();
Update :
Use below Code for 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();
You can simply inject this information:
public class MyLibrary : IMyLibrary
{
public MyLibrary(string assemblyName) { ... }
}
By registering it as follows:
container.RegisterSingleton<IMyLibrary>(new MyLibrary(
Assembly.GetExecutingAssembly().GetName().FullName));
Or in case you need to use Auto-Wiring (because MyLibrary
contains other dependencies, extract the configuration value into a configuration object:
public class MyLibraryConfig
{
public readonly string AssemblyName;
public MyLibraryConfig(string assemblyName) {
this.AssemblyName = assemblyName;
}
}
public class MyLibrary : IMyLibrary
{
public MyLibrary(MyLibraryConfig config, IOtherDependency dep) { ... }
}
With the following configuration:
container.RegisterSingleton(new MyLibraryConfig(
Assembly.GetExecutingAssembly().GetName().FullName));
container.Register<IMyLibrary, MyLibrary>(Lifestyle.Singleton)
Try something like:
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;
Haven't tested it though, the idea is to walk the methods until you find a known method from the library like the example looks for a Main method from a console app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.