I want to "hot" load some pre-packaged assembli(es) into a separate AppDomain, the thing however is I do not know the name of the entry point class or even the assembly file. I need to find this entry point so I can run some initialization routine.
So what I intend to do is to run ReflectionOnlyLoad on all the files and find the one that follows a certain convention ie. annotated/implements a certain interface etc.
Question is, will I start leaking memory if I were to run ReflectionOnlyLoad from the main AppDomain over and over? If this can't be run from the main app domain, what are my options, because again I do not know where the entry point is.
Also any additional information about the subtleties in using ReflectionOnlyLoad is appreciated.
I recommend Mono.Cecil. It's a simple assembly you can use on .net (it doesn't require the Mono runtime). It offers an API to load assemblies as data, and works pretty well. I found the API easy to work with, and it suffered from none of the problems I experienced when using reflection-only-load.
You can also use CCI, which is an open source project by MS that offers an assembly reader.
See also: CCI vs. Mono.Cecil -- advantages and disadvantages
ReflectionOnlyLoad won't solve your problem, see docs
Why don't you execute the code for finding the entry point etc. in the new AppDomain?
Cannot reflect through the dlls. Even with reflection only load, the type sticks to the main AppDomain.
2 Solutions:
Put the entry point in an xml somewhere and parse that.
Use a
2 stage AppDomain, one for the reflector, and then another for the
actual object.
I picked (1) since it's the most sensible.
(2) I have to pass through 2 separate proxies in order to issue command to the actual remote object, that or I need to couple the interfaces much more closely than I like. Not to mention being a pain to code.
Related
I am not sure the best way to explain this so please leave comments if you do not understand.
Basically, I have a few libraries for various tasks to work with different programs - notification is just one example.
Now, I am building a new program, and I want it to be as lightweight as possible. Whilst I would like to include my notification engine, I do not think many people would actually use its functionality, so, I would rather not include it by default - just as an optional download.
How would I program this?
With unmanaged Dlls and P/Invoke, I can basically wrap the whole lot in a try/catch loop, but I am not sure about the managed version.
So far, the best way I can think of is to check if the DLL file exists upon startup then set a field bool or similar, and every time I would like a notification to be fired, I could do an if/check the bool and fire...
I have seen from the debug window that DLL files are only loaded as they are needed. The program would obviously compile as all components will be visible to the project, but would it run on the end users machine without the DLL?
More importantly, is there a better way of doing this?
I would ideally like to have nothing about notifications in my application and somehow have it so that if the DLL file is downloaded, it adds this functionality externally. It really is not the end of the world to have a few extra bytes calling notification("blabla"); (or similar), but I am thinking a lot further down the line when I have much bigger intentions and just want to know best practices for this sort of thing.
I do not think many people would
actually use its functionality, so, I
would rather not include it by default
- just as an optional download.
Such things are typically described as plugins (or add-ons, or extensions).
Since .NET 4, the standard way to do that is with the Managed Exensibility Framework. It is included in the framework as the System.ComponentModel.Composition assembly and namespace. To get started, it is best to read the MSDN article and the MEF programming guide.
You can use System.Reflection.Assembly and its LoadFile method to dynamically load a DLL. You can then use the methods in Assembly to get Classes, types etc. embedded in the DLL and call them.
If you just check if the .dll exists or load every .dll in a plugin directory you can get what you want.
To your question if the program will run on the user's machine without the dlls already being present - yes , the program would run. As long as you dont do something that needs the runtime to load the classes defined in the dll , it does not matter if the dll is missing from the machine. To the aspect you are looking for regarding loading the dll on demand , I think you are well of using some sort of a configuration and Reflection ( either directly or by some IoC strategy. )
Try to load the plugin at startup.
Instead of checking a boolean all over the place, you can create a delegate field for the notification and initialize it to a no-op function. If loading the plugin succeeds, assign the delegate to the plugin implementation. Then everywhere the event occurs can just call the delegate, without worrying about the fact that the plugin might or might not be available.
I've a c# .net WPF application, now i need to register something(basically kernel of NInject IoC pattern) that has been used by the BLL and DAL layer.
I want to know the entry point or something like that for the dll where i could put that code(kernel registration).
For WPF section, i use App.xaml.cs, for WCF section i use Global.asax.cs as they are the entry point of these things. But what about standalone dlls, what is their entry point.
One approach is that, i could add a static class in my dll which fulfil this purpose and from app.xaml.cs i call this method of BLL and register my kernels. But this seems more like a workaround than approach.
Please guide me for something more to the point and logical.
Container configuration is done in the composite root of your application (The point where your code is called the first time). As you already said, in case of WPF this is the App.xaml.cs. Here you register the components of ALL layers. Preferably you have to UI code in another assembly than the App.xaml. This way the creation of the spplication is completely separated from the execution of the code.
I suggest to read Mark Seemans book where this is described in detail.
C# doesn't allow to run code on assembly loading, and static class constructors are lazily executed on first access to the class. However the CLR supports a static "assembly constructor", so to speak, which is executed when the assembly is first loaded. Mind you, references are still loaded lazily unless you put in special attributes to mark a referenced assembly to be loaded eagerly.
If you want you could put a static constructor into the assembly module through ildasm/ilasm. You could probably make some scripts to automate this on build.
I didn't do this myself yet, so I can't give any examples. Though if you consider doing it I can maybe dig up some links.
It almost sounds like your wanting a "plug-in" model where the app can dynamically discover components that are available. If so, then MEF might be a better option.
MEF seems to work well for cases where the app might not know about all it's dependencies ahead of time. Dependency injection, on the other hand, assumes that your app is fairly knowledgeable about these dependencies ahead of time.
I don't know if this is what you're after, but it might be worth a look.
I have got a dll placed in a shared folder over development server. Is there any way to use that dll without adding reference in my application and without installing the same in GAC.
Thanks in advance.
Assembly asm = Assembly.LoadFrom(path);
See MSDN for late binding, reflection etc.
Small edit: A variable with the keyword "as" is asking for trouble. So "Assembly as" changed to "Assembly asm" should be safer.
You may want to look at the Managed Extensibility Framework or at Assembly.Load... in the base framework.
Why would you want to do this, though? You'd need to call any code within the Assembly via reflection (hence the suggestion that the MEF may be what you're really after).
Yes, it is possible...somehow. Have a look at the Assembly-Class. With it you can load assemblies from a file without knowing what you exactly load.
Using Assembly.LoadFrom would be the only way to have zero references, but you'd still need to share contracts.
What's the problem with adding a reference?
What are you going to do when someone wants to work on a laptop and the WiFi goes down?
Yes,
you can call Assembly.Load() and then make use of Reflection to call into the public interface (lowercase "interface" - what I mean is the methods, fields and properties) exposed by the assembbly.
But in order to do that you need to know what methods to call. It helps if you can be certain that the assembly includes classes that do conform to a known .NET interface.
This idea is the basis for "plug-in" architectures in many tools, where the tool loads any assembly in its "plugin" directory, instantiates classes, casts the result to an ISomething, and then invokes methods via that interface.
I also would read Suzanne Cook's .NET CLR Notes.
http://blogs.msdn.com/suzcook/default.aspx
If this assembly is in a shared folder, you may find that .NET security restrictions stop you working with classes in that assembly in quite the way you'd expect.
Rather than storing on a shared folder, you may want to consider checking in the assembly to your source code repository. (I've seen a "/lib" folder used to good effect for this). Then you can reference the assembly directly.
(There are also repository solutions such as Maven that can more properly control this. However, they don't play well with .NET, unfortunately.)
I am working on an application that loads plugins at startup from a subdirectory, and currently i am doing this by using reflection to iterate over the types of each assembly and to find public classes implementing the IPluginModule interface.
Since Reflection involves a performance hit, and i expect that there will be several plugins after a while, i wondered if it would be useful to define a custom attribute applied at the assembly level, that could be checked before iterating over the types (possibly about a dozen types in an assembly, including 1 implementor of IPluginModule).
The attribute, if present, could then provide a method to return the needed types or instances, and iterating over the types would then only be a fallback mechanism. Storing the type info in a configuration file is not an option.
Would this improve performance, or does it just not matter compared to the time to actually takes to load the assembly from storage? Also, would this usage be appropriate for an attribute at all?
I will answer your question with a question: Why are you worried about this?
You're worrying about a potential performance hit in a one time operation because there might be several plugins at a later date.
Unless your application startup time is excessively long to a user, I wouldn't waste time thinking about it - there are probably much better things that you can work on to improve your application.
You could also have the plugable types in a configuration, so you know the exact classes instead of looping through all classes. Would have to have some configuration utility for this option...but could possibly get a good increase in performance depending on the number of classes you are looping through.
I believe both of Microsoft's two .net plugin frameworks, the Managed AddIn Framework (MAF) and the Managed Extensibility Framework (MEF) can use either attributes or reflection to discover plugins. So Microsoft seems to feel attributes are appropriate.
I'm not sure what the performance differences are, though.
A good solution is to cache all information about plugins. The first time the application is started it does a full scan of the plugin dlls, and saves the list of types found in a file. The next time the application starts, it loads the information from the file, which will be much faster than scanning all the dlls again. The application can also store a timestamp of each dll, so if it detects a change in a dll it can re-scan it and update the cache.
That's basically the approach followed by the Mono.Addins framework.
I'd have thought that asking an assembly for all the classes that are tagged with an attribute would also use reflection. It would then come down to which is a faster look up in the metadata, interface implementation or attribute marking?
I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.
What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.
As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.
What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:
String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:
AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.
So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.
I know that tools like Reflector do this, I just can't find the syntax for getting at it.
Couple of options here:
Attach to AppDomain.AssemblyResolve and do another LoadFile based on the requested assembly.
Spin up another AppDomain with the directory as its base and load the assemblies in that AppDomain.
I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see Assembly.ReflectionOnlyLoad).
I worked out Kent Boogaart's second option.
Essentially I had to:
1.) Implement the ResolveEventHandler in a separate class, inheriting from MarshalByRefObject and adding the Serializable attribute.
2.) Add the current ApplicationBase, essentially where the event handler's dll is, to the AppDomain PrivateBinPath.
You can find the code on github.