Related
I have to create objects for a particular class at runtime, the classes should be configured in the app settings of the web.config file, using Reflection.
The problem is, I am not able the Load the assembly. Since the classes are in the referenced dlls. I am not able to get the actual path of the referenced dll.
I Have tried Path, CodeBase, Current Directory. Can someone help me??
If the assembly is referenced by the project, you don't need to load it. You can get it by getting the Type of a class which is in that particular assembly.
In general, doing Late-Binding on your own, isn't the best of an idea. We had some issues with that at our project and it's quite a lot of work to do it right. You could instead use some of the many different IoC-Containers, which will find the assembly and also the class for you.
EDIT:
I was maybe a bit confused, that I didn't think of it earlier. You can simply load an Assembly by it's name. Than it should find the assembly in all the referenced paths or the GAC.
Further information can be found at MSDN
I have a solution containing several projects.
There is one project that references all other projects, there may be references between these referenced projects as well.
Let's assume project A as the main one.
Project B has a MyType class.
Project C has an extension method for MyType.
Each assembly has an attribute. It allows me to determine if the assembly is mine or an external library (maybe it's not the best way to do it, but it works).
At some point in A I have a mechanism that uses reflection to find all extension methods of MyType. To do that I handle event AppDomain.AssemblyLoad to create a list of my loaded assemblies (marked with an attribute). Then I can scan the assemblies for proper extension methods.
Unfortunately, at this moment C is not loaded, because nothing from C has been called. Thus, the extension is not found.
I've tried using Assembly.GetExecutingAssembly().GetReferencedAssemblies(), but I think it returns only loaded assemblies, no luck here.
My final solution in A is:
public static void Main(string[] args)
{
TypeFromProjectC temp;
//further code...
}
It works because the assembly gets loaded on temp declaration, but...
I could try to load assemblies by path/name, but let's assume it's not an option. I want to create a generic solution that would not need to be altered each time I add another reference. In fact that is why I have added this attribute for my assemblies.
Something like GetReferencedAssemblies() would be great. It would be the best if I could check the assembly for my attribute before calling Load(), but it's not that necessary. (Does it even makes sense? When I think of it now, I'd guess that it must be loaded before the attributes are available, but maybe some meta information could do?)
It's the first time I'm playing with multiple assemblies with quite a complicated structure, so it's possible that I don't really have a clue how does it work and my question is plainly stupid.
I hope it's not ;]
Some notes and comments before my answer:
1) You have a reference to ClassLibrary1 and ClassLibrary2, and instantiate Class1 from ClassLibrary1. In that case compiler throws away reference to ClassLibrary2 and Assembly.GetReferencedAssemblies() returns to you actual optimized list of references. When you use any type from ClassLibrary2, complier will respect that reference also. The best way for making strong refs is:
static class StrongReferencesLoader
{
public static void Load()
{
var ref1 = typeof(Class1); // ClassLibrary1.dll
var ref2 = typeof(Class2); // ClassLibrary2.dll
}
}
This allows to reference static classes also and this allows to force loading of every strong-referenced library by calling this method.
2) You do use an AppDomain.AssemblyLoad event. Consider subscribing here from your entry point. Be careful, because if your entry point make something else this can lead to loading assembly before subscribing occurs.
class Program
{
static void Main()
{
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
new Class1();
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Console.WriteLine("! " + args.LoadedAssembly.FullName);
}
}
in this sample, you will not get an output about loading ClassLibrary1, because loading of library was performed before executing main method. Runtime loads all necessary libraries for executing specified method. If we extract this call to another method - everything become fine.
class Program
{
static void Main()
{
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
RealMain();
}
static void RealMain()
{
new Class1();
}
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Console.WriteLine("! " + args.LoadedAssembly.FullName);
}
}
In that case, Main is executed without problem, and subscribes immediately. After that, assembly loading performed due to call RealMain that contain a byte-code referenced to ClassLibrary1, and your event handler works.
3) Note that in any time you can list all loaded assemblies by AppDomain.CurrentDomain.GetAssemblies()
I'm not fully understand your problem. Is that only solution-wide analysis, or generic idea for future plugins, created by any one else? Solution-wide analysis can be solved in compile-time or run-time, but open plugin system is only runtime.
Run time solution
First of all, you should understand that it is impossible to detect every plugins. Let say, Class1 have extensions, written by some body for another application and installed in another directory:
some pseudo-structure:
\GAC\ClassLibrary1.dll
\ProgramFiles\MyApp\ConsoleApplication1.exe // our entry point
\ProgramFiles\SomeApp\ClassLibrary3.dll // some library from another solution, that references shared ClassLibrary1
You can detect plugins in your GAC, AppDomainBase path, RelativeSearchPath (all of that done by built-in assembly resolver), any custom hardcoded path, and paths of already loaded assemblies AppDomain.CurrentDomain.GetAssemblies().Select(x => Path.GetDirectoryName(x.Location)).Distinct();
And you can analyse that paths recursively.
But you'l never find path like \ProgramFiles\SomeApp\ClassLibrary3.dll unless you scan entire computer.
I hope, that searching in deep to already loaded assemblies location can solve your problem.
Note that you can use Mono.Cecil, but it is convenient to use Assembly.ReflectionOnlyLoad for that purpose. You can load by file name using Assembly.ReflectionOnlyLoadFrom, and you can help resolve assemblies in another location by AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve event. But you can not use that for custom attributes analysis. In that case some hack is required, like special class name (static class MySuperMark{}), which existance can be checked with easy. It is less hacky to use special interface that every plugin required to implement (but it is not so close to your case).
Compile time solution
Only for solution-wide analysis.
Since you have noted, that
I want to create a generic solution that would not need to be altered each time I add another reference.
Probably you are looking for solution-wide answer. I can suggest some metaprogramming here. Usually I'm solving such task by metacreator http://code.google.com/p/metacreator/. You can run some piece of code before compilation of ConsoleApplication1. For example, you can create a class holding strong references for every referenced dlls automatically by metacode and you can run such class for ensuring early loading of referenced assemblies. This class will actualized on every compilation automatically.
Please, describe more details, which case I can describe more deeply.
In my opinion, assembly analysis with Mono.Cecil is useful here. For example you can enumerate references (of course without ones deleted from project by compiler) without loading given assembly and any of its references by:
var assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly("protobuf-net.dll");
foreach(var module in assembly.Modules)
{
foreach(var reference in module.AssemblyReferences)
{
Console.WriteLine(reference.FullName);
}
}
Such code prints:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Runtime.Serialization, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
However IMO better idea is to scan through directory, possibly containing plugins and check them for your attribute using Cecil and therefore without loading (because you do not know at that point whether you want to load them at all):
var assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly("protobuf-net.dll");
foreach(var attribute in assembly.CustomAttributes)
{
Console.WriteLine(attribute.AttributeType.FullName);
}
There are couple options for comparing your attribute (which is a class from loaded assembly) to Cecil's attribute description, full type name is one of them.
Assembly.GetReferencedAssemblies() gives you a very reliable list of assemblies that your code actually uses. You will have to recurse through the list so you will find all of them, not just the ones that you main .exe assembly uses.
What you'll get does not necessarily match the assemblies you added with Project + Add Reference. The compiler makes sure to only include referenced assemblies in the metadata that your code actually uses. Which is perhaps why TypeFromProjectC temp; works.
If there are other assemblies lying around that ought to be loaded but are not found by recursing through GetReferencedAssemblies() then you have to load them yourself explicitly with Assembly.Load/From(). Actually using types from such assemblies has to be done manually too, using Activator.CreateInstance() to create an object and Reflection to call methods etcetera.
There's no evidence in your question that you actually intend to use Reflection, especially because you mention extension methods. An extension method that actually gets used in your code will always end up producing an assembly that's discovered through ReferencedAssemblies(). It is also fairly unclear why you want to do this in the first place. The just-in-time compiler is already very good at loading assemblies on demand, doing so when it compiles code just in time. Which is almost always desirable since it turns a long startup delay you'd get by forcing the CLR to find all assemblies into a hundred needle pricks that the user won't notice. Lazy assembly loading is very much a feature, not a bug.
If you don't have a static, compile-time reference to an assembly, directly or indirectly, such an assembly is not going to get loaded and thus is invisible to your enumeration logic. It is possible, however, to dynamically load all assemblies in, say, a particular directory at run-time.
On the other hand, I don't believe there is a place for a system-global dictionary of assemblies that might have a particular custom attribute, which seems to be what you're asking for.
You are looking for your ext methods so the referenced assemblies can be found int the following locations:
the sub directories of the executing asm - simple to implement
sub directories of called asms - simple to implement using the assembly loaded event
mainfest - you have to figure this one out but I dont think it is that hard. Just parse the xml and read the elements
GAC - if you register your asms in the GAC. The solution can be found here:Extract assembly from GAC
Is there a way to reference a library without a strong name?
When I add a reference to the assembly in references and rebuild solution everything is fine, but when I call the class from this assembly solution it doesn't build.
Output says that referenced assembly should have strong name. What is the best solution? Strong naming library is not preferable.
I think the problem you have here is that the assembly you are trying to add the reference from is being signed with a strong name but the assembly you are trying to reference is not signed. A strong-named assembly can only reference other strong-named assemblies.
Either sign the assembly you are referencing or don't sign the assembly that is referencing it.
The reason why the error only appears when you actually call the class is because the compiler will strip out the reference in the compiled output if there is no code actually invoking the referenced assembly.
If it's the case that you really can't either add a strong name to the one being referenced, or remove the strong name from the one doing the referencing (sorry long-winded) then you are going to have to look at binding the class at runtime via reflection and then accessing it via a common base or interface - not ideal at all; or even worse actually invoking it via reflection, or dynamic.
The whole point of a strong name is that you know what dlls are getting loaded. You can't add a strong-name to your dll if you reference something that isn't strong-named, as anything could be loaded in place of the dll you are thinking of (as long as the name matches). This entirely defeats the guarantees that a strong name is intended to provide.
So (one of):
don't add a strong-name to your dll (for most internal things, you just don't need one)
or; rebuild the dll you are referencing with a strong-name
or; load the additional dll only through reflection (yuck)
In msvc i can write
#pragma comment(lib, "my.lib");
which includes my.lib in the linking stage. In my solution i have 2 projects. One is a class project the other is my main. How do i include the reference dll in code instead of adding the reference in the project?
Contrary to popular belief, it is possible :-)
To statically link .NET assemblies check out ILMerge. It's a utility that can be used to merge multiple .NET assemblies into a single one. Be it an executable or a DLL.
You could create a batch script that packages your assemblies together as a post-build step.
Edit: One thing to note however is that this does not remove the need to reference the library. The reference is still needed in order to compile your code that is dependent the external types. Much like including header files under C(++). By default c# assemblies are independent, there is no linking involved. However the tool I mentioned above allows you to create a new assembly with the external dependencies included.
As far as I know, you can't. If you need to access type that are included in a non referenced assembly, you'll have to use Assembly.Load().
I'm afraid you can't.
You can dynamically load the assembly via Assembly.Load(...) but then you have use reflection to explicitly create each Type you need to use.
I don't think you can include a dll from code without adding a reference. What you can do however is to use reflection to load that assembly and use a type from that assembly.
Assembly.Load() will get you a handle on the assembly and then you should be able to iterate through the types in the assembly.
Managed code doesn't use a linker. The C/C++ equivalent of a reference assembly is the #include directive, you need that in C/C++ to allow the compiler to generate code for an external type. Exact same thing in C#, you can't use an external type unless the compiler has a definition for it. The reference assembly supplies that.
The equivalent of C/C++ linking is done at runtime in a managed program. The JIT compiler loads assemblies as needed to generate machine code.
One thing you can do in a C# program that you can't do in a C/C++ program is using Reflection. It allows you to invoke a constructor and call a type's methods with type and method names as strings. Start that ball rolling with Assembly.GetType() and the methods of the Type class. However, consider a plug-in model with, say, the System.AddIn namespace first.
If you want to load an assembly at runtime, you can use Assembly.LoadFrom(filePath). But that way you are not referencing the assembly, and you can't use strong typing.
For example, you can have different plugins implementing a known interface (the one which is in a separate, referenced assembly), and have them all placed in a folder. Then you can check the folder and load all implementing classes at runtime (like in this example).
If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource?
I.e. instead of having MyAssembly.dll, SomeAssembly1.dll and SomeAssembly2.dll sitting on the file system, those other two files get bundled in to MyAssembly.dll and are usable in its code.
I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET? Are all .NET assemblies DLLs, but not all DLLs are .NET assemblies? Why do they use the same file format and/or file extension?
ILMerge does merge assemblies, which is nice, but sometimes not quite what you want. For example, when the assembly in question is a strongly-named assembly, and you don't have the key for it, then you cannot do ILMerge without breaking that signature. Which means you have to deploy multiple assemblies.
As an alternative to ilmerge, you can embed one or more assemblies as resources into your exe or DLL. Then, at runtime, when the assemblies are being loaded, you can extract the embedded assembly programmatically, and load and run it. It sounds tricky but there's just a little bit of boilerplate code.
To do it, embed an assembly, just as you would embed any other resource (image, translation file, data, etc). Then, set up an AssemblyResolver that gets called at runtime. It should be set up in the static constructor of the startup class. The code is very simple.
static NameOfStartupClassHere()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolver);
}
static System.Reflection.Assembly Resolver(object sender, ResolveEventArgs args)
{
Assembly a1 = Assembly.GetExecutingAssembly();
Stream s = a1.GetManifestResourceStream(args.Name);
byte[] block = new byte[s.Length];
s.Read(block, 0, block.Length);
Assembly a2 = Assembly.Load(block);
return a2;
}
The Name property on the ResolveEventArgs parameter is the name of the assembly to be resolved. This name refers to the resource, not to the filename. If you embed the file named "MyAssembly.dll", and call the embedded resource "Foo", then the name you want here is "Foo". But that would be confusing, so I suggest using the filename of the assembly for the name of the resource. If you have embedded and named your assembly properly, you can just call GetManifestResourceStream() with the assembly name and load the assembly that way. Very simple.
This works with multiple assemblies, just as nicely as with a single embedded assembly.
In a real app you're gonna want better error handling in that routine - like what if there is no stream by the given name? What happens if the Read fails? etc. But that's left for you to do.
In the rest of the application code, you use types from the assembly as normal.
When you build the app, you need to add a reference to the assembly in question, as you would normally. If you use the command-line tools, use the /r option in csc.exe; if you use Visual Studio, you'll need to "Add Reference..." in the popup menu on the project.
At runtime, assembly version-checking and verification works as usual.
The only difference is in distribution. When you deploy or distribute your app, you need not distribute the DLL for the embedded (and referenced) assembly. Just deploy the main assembly; there's no need to distribute the other assemblies because they're embedded into the main DLL or EXE.
Take a look at ILMerge for merging assemblies.
I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET?
Yes.
Are all .NET assemblies DLLs,
Either DLLs or EXE normally - but can also be netmodule.
but not all DLLs are .NET assemblies?
Correct.
Why do they use the same file format and/or file extension?
Why should it be any different - it serves the same purpose!
You can embed an assembly (or any file, actually) as a resource (and then use the ResourceManager class to access them), but if you just want to combine assemblies, you're better off using a tool like ILMerge.
EXE and DLL files are Windows portable executables, which are generic enough to accomodate future types of code, including any .NET code (they can also run in DOS but only display a message saying that they're not supposed to run in DOS). They include instructions to fire up the .NET runtime if it isn't already running. It's also possible for a single assembly to span across multiple files, though this is hardly ever the case.
Note ILMerge doesn't work with embedded resources like XAML, so WPF apps etc will need to use Cheeso's method.
There's also the mkbundle utility offered by the Mono project
Why do they use the same file format and/or file extension?
Why should it be any different - it serves the same purpose!
My 2ยข bit of clarification here: DLL is Dynamic Link Library. Both the old style .dll (C-code) and .net style .dll are by definition "dynamic link" libraries. So .dll is a proper description for both.
With respect to Cheeso's answer of embedding the assemblies as resources and loading them dynamically using the Load(byte[]) overload using an AssemblyResolve event handler, you need to modify the resolver to check the AppDomain for an existing instance of the Assembly to load and return the existing assembly instance if it's already loaded.
Assemblies loaded using that overload do not have a context, which can cause the framework to try and reload the assembly multiple times. Without returning an already loaded instance, you can end up with multiple instances of the same assembly code and types that should be equal but won't be, because the framework considers them to be from two different assemblies.
At least one way that multiple AssemblyResolve events will be made for the same assembly loaded into the "No context" is when you have references to types it exposes from multiple assemblies loaded into your AppDomain, as code executes that needs those types resolved.
https://msdn.microsoft.com/en-us/library/dd153782%28v=vs.110%29.aspx
A couple of salient points from the link:
"Other assemblies cannot bind to assemblies that are loaded without context, unless you handle the AppDomain.AssemblyResolve event"
"Loading multiple assemblies with the same identity without context can cause type identity problems similar to those caused by loading assemblies with the same identity into multiple contexts. See Avoid Loading an Assembly into Multiple Contexts."
I would suggest you to try Costura.Fody. Just don't forget to Install-Package Fody before Costura.Fody (in order to get the newest Fody!)