Dependency Injection and loading dependent assembly in .NET - dependency-injection

I'm working with dependency injection (DI from now on) to resolve components and am looking for an elegant solution to loading dependent assemblies in a .NET environment. As an explanation, lets say that we have 3 assemblies, A, B and C, where A depends on B and B depends on C. Now I need to load components from assembly A, but because I am using DI, I don't have a reference to assembly A. And even a reference to assembly A wouldn't be enough because I somehow need to ensure that A, B and C all end up in my output directory.
So, some obvious solutions are to:
- add references to A, B and C from the executing application: Requires knowledge of the dependency structure which, in my case, is extremely complex, making this a somewhat undesired solution.
- add these dlls to the GAC: Just not an option in my case.
So I'm wondering if anyone has an elegant solution to this issue. Not sure if it's relevant but I'm using Castle Windsor for DI.
Thanks
Joni

There is an event called AssemblyResolve on your AppDomain that gives you a chance to load missing assemblies. This lets you load your missing assembly from any stream you provide such as a file in a different folder or a file stored in a database.

What would it buy you to load the assemblies dynamically?
You should just add references to A, B, and C in the executing application, unless you're writing an application designed to be extended by other parties, or you have to change the dependencies extremely frequently.
Otherwise, you're solving a trivial problem (the need to recompile to deploy changes) by introducing a different problem (the possibility of failing at runtime).
Think of the list of references as your application's constructor arguments - your application should clearly declare its dependencies instead of tucking them away in a config file.

If the only issue you have is getting the assemblies in the output directory than it's not a Windsor question - it's a MsBuild question (or NAnt or whatever you're using to build your project). Just have your script do it.
If you're looking at extensibility scenario, that is you have the assemblies in the directory and you want to load them, Windsor 2.5 (current trunk) has some pretty nice support for this as well, both from XML and from fluent API.

Related

Isolate modules within one F# project using folders - is it possible?

I like the way F# requires to organize files and code in order of dependency because it discourages mindless coupling.
I have flat list of source files atm (simplified):
Common.fs
Workflow1.fs
Workflow2.fs
And want to go one step beyond. First, organize files like this (VS 2017 can't move folders up and down, one needs to edit .fsproj but it is different story - at least it is possible):
Common.fs
Workflow1\Impl1.fs
Workflow2\Impl2.fs
I expected Impl1.fs and Impl2.fs to be fully isolated from each other because their folders are not in parent/child relationship, but Impl2.fs can easily see types and functions from Impl1.fs: just open module and they are available
Are there any techniques to keep them isolated? It's possible to split the project in three however I prefer to keep DLL as a unit of deployment: workflows are small and ideally I want to avoid to have many tiny DLL files.
It sounds like you have a good understanding of what your options are. You are not missing anything else. Consequently, the answer to your question is, "no."
You can't isolate the folders that way, as far as I know. However, if you want to keep them isolated at compile time but deployable as a single unit, you can create separate projects and use Fody or ILMerge to combine the assemblies post-compilation.

.NET Assembly Loading with Strong Name

How to load the assemblies (example my service layer assemblies) into my MVC application from a location (directory) other than the Bin folder (I dont want to register in GAC)
Can I have a strong name common across all my assemblies I use in my application. Any Disadvantages of having a common strong name for all assemblies?
You can use Assembly.LoadFromFile() with any path. Could be a bit tricky though if the assembly to load requires other libraries which are stored in your default bin folder. It normally works, but I've also seen problems arising there (especially also in unit tests etc.).
What do you mean by "one strong name"? Using the same keyfile for all assemblies? Yes, that's definitely acceptable.

StructureMap configuration: Options to minimize dependencies on the StructureMap assembly

I understand how to implement a StructureMap registry, my question concerns the fact that every project that contains a StructureMap registry requires a static reference to the StructureMap assembly. Is there a best practice for how to structure the configuration for a large number of projects (30+) without forcing each project to take this dependency?
The alternative, I suppose, would be to create a bootstrapper assembly that could be referenced by the host process. The bootstrapper would perform all wire-up. In this scenario, the bootstrap assembly, instead, would have references to all of the projects. This has the upside of centralizing the reference to StructureMap so that all of the projects are unaware of StructureMap.
Using XML-based configuration is not an option for me.
Are there any other options for configuration that minimize the number of static references the projects in the solution must take? I'm guessing that there isn't, but thought I'd solicit some other opinions.
Technically, you only need a single project to reference the container framework, and that is the top-level application project. It references all the other projects and specifies the configuration of the components.
This puts the entire graph configuration out of the hands of each project, opting instead to define graphs only where they are used. This gives each application the complete freedom to configure components, rather than assuming the components will be used in the same way every time (as is implied by the registries which are inherent to each project).
An aside that may or may not be useful: in quantum physics, when we observe a particle, we collapse it from every possible state into a particular one. Frameworks are similar, in that they don't exist in a single state until they are observed, which here means "put to use in an application." This frames the application as the observer, which is the context in which the framework collapses into a single form.
Now, I generally wouldn't want the application be responsible for both being a running application and also configuring that runtime. For this reason, I tend to have a Composition project which references the others as well as the container framework. The actual application project can then reference the Composition project. This externalizes the registries from each project, including the application project, producing a cohesive assembly whose sole purpose is to define the composition of a particular application.

Determining missing dependencies statically when using dependency injection container

When using a dependency injection container, missing dependencies are detected when you execute resolve. This is at runtime.
This article describes a partial solution. It would help simplify test, debug, and maintenance, but it still requires tests to be executed to validate your behavior (especially if you use the abstract factory sub-solution for runtime resolution):
http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx
When using dependency injection containers, is there a way to determine at statically that all of your dependencies will be resolved?
The Managed Extensibility Framework (MEF) can do this. There are some best practices that you need to adhere to in order for the analysis to be accurate, but the results are otherwise good.
To analyse a set of assemblies a command-line tool is used - see http://blogs.msdn.com/b/nblumhardt/archive/2009/08/28/analyze-mef-assemblies-from-the-command-line.aspx. This can be run from Visual Studio or a build script in a continuous integration server - http://blogs.msdn.com/b/nblumhardt/archive/2009/09/24/debug-composition-from-within-visual-studio.aspx.
You can do it visually (again over a set of assemblies) using the MefContrib project's Visual MEFX - see http://xamlcoder.com/blog/2010/04/10/updated-visual-mefx/
MEF supports this functionality by being both very declarative (standard attributes for configuration) and by using an underlying composition model that works lazily (it can build the graph without creating any instances... Takes a bit to wrap your head around.)
Short answer: no, it can't be done.
Doing this would require being able to represent all components and their dependencies (the container metadata) as a graph, in order to analyze it. Problem is, the more sophisticated the container, the harder it gets to achieve this. Take for example Windsor. Its numerous extension points make the dependencies too dynamic to be represented as a graph. Lazy component loaders, handler selectors, factories, componentmodel contributors, subresolvers, all participate in the process and they can be arbitrary user code, which makes it impossible to analyze statically.
A static analysis might be feasible for a trivial container, but then this hypothetical container would be pretty useless for real-world projects.
So as usual it's a trade-off, and the best we can do is have some tests that exercise the actual resolution of all registered components in the container. StructureMap has a AssertConfigurationIsValid() method to do just that.
Even so, there could be more subtle errors that are not caught by this, such as lifestyle issues.
In addition to what Mauricio said, Windsor 2.5 has a feature that you might find useful when diagnosing issues with missing dependencies or just looking through the components in the container.
I blogged about beta version of it here. It's now quite more useful and as everything in Windsor - it's extensible so you can out your own items on that list.
Maybe not with a dependency injection container. However, you can do dependency injection manually, without a container. For example:
var foo = new Foo();
var bar = new Bar(foo);
var program = new Program(bar);
program.Run();
If it compiles then all the dependencies are there.
However, trouble looms as soon as the dependency graph grows large enough that you can't keep it entirely in your head (espcially with some circular dependencies thrown in the mix). If you do refactorings that involve rearranging of dependencies, then it will become hard work to adapt the order of constructor calls.

dependency browser that runs against an inversion of control framework

Do any inversion of control / dependency injection framworks support viewing the object dependencies that have been registered? This is not to execute the code, but to better understand it. It seems that a graph based on the information it has (class A depends on B and C, class B dependencs on C and E, etc) would really document a system well.
I'm using Castle Windsor at the moment, but wouldn't mind trying a different framework for this functionality.
For Spring the Spring IDE shows you a dependency graph.
For Guice you can use Grapher.
Here's a little console application that'll output the dependency graph of a Windsor container. Text-only, but still very useful.
I recently blogged about showing all component dependencies as a proper graph. Sample output (scaled down):

Resources