Entry Point of a DLL - c#

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.

Related

How to handle dll dependency that may not be present? [duplicate]

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.

How to reference to assembly in mvc at runtime

In my Asp.Net MVC application, i have some view file (.cshtml) which has reference to an external library which it will be loaded at runtime. so after app started, i load the assembly by Assembly.Load and i register the controllers by my own custom ControllerFactory and every thing is ok.
But, in some views which has references to the dynamically loaded assembly, throws the :
Compiler Error Message: CS0234: The type or namespace name 'MyDynamicNamespace' does not exist in the namespace 'MyApp' (are you missing an assembly reference?)
exception that tells the razor compiler cannot resolve the related assembly.
My question is that, is there a way to register the assembly at runtime, to able the razor compiler can access to it and resolve it?
Notice that i can't use BuildManager.AddReferencedAssembly method because my assembly have to be loaded after app start, and the BuildManager does not support it.
1) I wouldn't recommend having your views directly use external references or dynamically loaded external references. Abstract this by having your view interact with a controller. Make your controller feed a data object to your view that is known at build time by your application (in other words, an object known to your web application at build time). This is to completely isolate (abstract) plugin specific business from your view. Then make your controller interact with the "plugin".
2) I don't know how your "custom factory" works but nowadays we don't really build any "custom factories" anymore. Instead we leverage dependency injection containers such as Microsoft Unity(or Ninject, or Castle Windsor or etc..). Creating "custom factories" is very old fashioned and you're basically reinventing the wheel that has been solved with dependency injection.
3) As far as dynamically loading external assemblies, I don't know if you have it right but here's a link:
Dynamically load a type from an external assembly
4) Typically, a plugin design exposes interfaces that are known to your main web application at build time. What the plugin design hides is the implementation which can change from one plugin to another. The important thing is that each plugin implements the same public interfaces, those that are expected by your main web app. Usually, you will have those interfaces in a separate "Common" project that is referenced by both, your main web application and your plugin that implements those interfaces. Therefore, from your main web app, you will know what the public interfaces of your plugins are, you can dynamically load the external assembly and use C# reflection to find the classes that implements those interfaces and load them into your dependency injection container. Likewise, anyone who will want to develop of a plugin for your web app will have to implement the interfaces that are defined in your "Common" project.
Note: "Common" is just a random name I gave to the project. You can name it "PluginInterface" or whatever you want.
After that, having your controller grab whatever it needs from the dependency injection container is trivial.
Note: Your plugin interfaces will probably have input and output entities. These entities are shared between your main web app and your plugin. In such case, since these entities are part of your interfaces they need to be in the "Common" project. You may be tempted to have your controller return those entities directly to your view but then you won't have a perfect abstraction between your view and your plugin. Not having perfect abstractions is for another discussion.
Hope it helps!
As a Sys Admin, I would recommend a maintenance period, especially if the file you replace messes something else up. Even if your maintenance period is only a half hour it is good practice.
As for the DLL and recompile... typically the IIS Worker Process (the service running your application pool) will recycle at normal intervals based on the IIS configuration and memory usage. When this happens the application will recompile if anything requires the JIT. It also terminates all open user sessions as it physically stops and then re-starts. The worker process also monitors the root directory (like you mentioned) for any file changes. If any are found a recompile is forced. Just because a dependency is changed does not force a recompile. If you pre-compile your DLL the only thing left to compile is any code inside of your actual ASPX file and this uses the JIT which compiles each time. From what you described IIS should not need to recompile or restart, sounds like another problem where IIS is hanging when you swap out the file. Might need to get a sys admin involved to look at the IIS logs.
Good Luck!
http://msdn.microsoft.com/en-us/library/ms366723.aspx
http://msdn.microsoft.com/en-us/library/bb398860.aspx
Here is a note that may helps: If you are not loading your assemblies from the /bin directory, you need to ensure that the path to the assemblies is discoverable:
AppDomain.CurrentDomain.AppendPrivatePath(path_to_your-dyna_assembly);

ReflectionOnlyLoad can it be garbage collected?

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.

IoC and "hiding implementation details"

I implemented DI in my project through constructor injection, now the composition root is where all resolving takes place (this is, at the web project), and my question is whether the idea of creating an additional project that just handles the resolving is insane.
The reasoning behind this is while I would still have the implementation assemblies in the build directory (because they would still be referenced by the "proxy" project), I wouldn't need to reference them at web project level, which in turn would mean that the implementation of these interfaces wouldn't be accessible from somewhere other than where they're implemented (unless explicitly referenced, which would quickly pinpoint that something is wrong: you don't want to be doing this).
Is this a purposeless effort likely to become error prone or is it a reasonable thing to do?
There are pros and cons of this. As BrokenGlass said, this is a litmus test, on the flip side you really have to be careful you deploy all of the assemblies. Since dependencies of included libs are not put into the bin folder of the web app, you'll need to ensure they aren't missed although upon first run you would experience this and the resolution would ideally be easy.
This is indeed a matter of personal preference, for ease I like to include in the web app, but again, it can ensure those dependencies don't leak to the web app. However if your project is organized in such as way where your controllers always inject what you require, then the chances of it happening are less. For ex, if you take IContext in every controller then you are less likely to use using(var context = new Context()) in your app, since the standard has been set.
This is not insane at all - it is a very good litmus test to make sure no dependencies have sneaked in and very useful as such. This would only work though if your abstractions / interfaces are defined in a different assembly than the concrete classes that implement those interfaces.
Having said that, personally I have always kept the aggregate root within the main web app assembly, there is extra effort involved in this extra assembly and since I for the most part only inject interfaces I am not too worried about it, since my main concern is really testability. There might be projects though for which this is a worthwhile approach.
You could do some post-build processing to ensure the implementation doesn't leak out.
Cheers
Tymek

How to create a loosely coupled architecture with hot-swap capability?

I'm interested in creating a desktop application composed of modules such that the source code to those modules is embedded in the application itself, allowing the user to edit the application as they are running it and have the updated modules put into use without restarting the application. Can anyone suggest a good architecture for this?
I'm looking to use Microsoft.Net and C# for this. DLR is not an option.
Thanks!
It's not easy to suggest a good architecture for this in a short posting.
At first, i'd define a contract (an Interface) every module the user writes/modifies must implement. It should contain at least an Execute method.
Then I'd create a Wrapper-Class for these modules which:
loads the source code from a file
The wrapper compiles the file and also makes sure it implements the contract
Contains an indicator of whether the file could be compiled sucessfully
It should also implement the contract, for easy calling and handling
Then I'd have some kind of shell which contains a collection of all the module-wrappers. Any wrapper that sucessfully compiled would then let the Shell call the Execute method of the module interface.
When it comes to compiling and executing code on the fly, this link should provide all the information you need:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
Well, a dynamic language certainly would have been the best fit...
You can use the types in the System.Reflection.Emit namespace to dynamically create assemblies.
However, it's going to be really painful because you'd need to load those dynamic assemblies into custom AppDomains because otherwise you'll not be able to unload them again.
This again means that you must address marshalling and assembly resolution issues related to cross-AppDomain communication.
What you are probably looking for is the concept of Dependency Injection.
Dependency Injection means that instead of having module X use module Y directly, module X only relies on an interface, and the application tells module X which implementation should use for it, e.g. using module Y.
There are several ways of implementing Dependency Injection. One is to have references to the interfaces in each of your modules, and explicitly let the application configure each of its modules with the right implementation of the interface.
The second wahy of implementing it (and probably the most useful in your case) is by using a central registry. Define all the interfaces that you want to have in your application. These are the interface for which you want to dynamically change the implementation. Then define identifications for these interfaces. These could be strings or integers or GUID's.
Then make a map in your application that maps the identifications to the interfaces, and fill the map with the correct implementations of the interfaces. In a C++ application (I'm not very skilled in C# yet) this could work like this:
std::map<std::string,IInterface> appInterfaces;
appInterfaces["database"] = new OracleDatabaseModule();
appInterfaces["userinterface"] = new VistaStyleUserInterface();
Make all modules go to this central registry whenever they want to use one of the modules. Make sure they don't access the modules directly, but they only pass via the registry. E.g.
MyModule::someMethod()
{
IDatabaseInterface *dbInterface = dynamic_cast<IDatabaseInterface *>(appInterfaces["database"]);
dbInterface->executeQuery(...);
}
If you now want to change the implementation for an interface in the application, you can simply change the entry in the registry, like this:
IInterface *iface = appInterfaces["database"];
if (iface) delete iface;
appInterface["database"] = new SqlServerDatabaseInterface();

Categories

Resources