StructureMap configuration: Options to minimize dependencies on the StructureMap assembly - dependency-injection

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.

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.

Dependency injection in Umbraco or unit testing

I have made a project in Umbraco using backoffice completely.But Now I am trying to apply concept of dependency injection(which I may have used in past..but not by that specific name) in that project.
and after loads of searching.I now know the concept of dependency injection(I think),in which we are supposed to use classes and constructor to restrict the input supplied to a function in terms of type,value.
But how am I suppose to make that umbraco project from that.I once tried making a strongly typed.It looks much like that which I am supposed to do now.
I also took reference from these articles.
Is it possible to use dependency injection with Umbraco 7 ContentService event handlers?
Why does one use dependency injection?
But still I am kind of stuck..Is there any other way to do unit testing in umbraco.
Yes, you can! :)
Basically, the starting URL for using IoC and DI with Umbraco was already shared. It's here: https://our.umbraco.org/documentation/reference/using-ioc. You can of course use any of the avaialable containers, the example is just for autofac. You just need to remember to initialize container when Umbraco starts (using event handlers).
For Unit Testing resources I would point you first to tests made by Umbraco itself: https://github.com/umbraco/Umbraco-CMS/tree/dev-v7/src/Umbraco.Tests. You can explore how the core team is testing their code and even reference this library and make use of it in your solution.
There are some other useful materials to start unit testing with Umbraco. To list a few:
http://blog.aabech.no/archive/the-basics-of-unit-testing-umbraco/
http://skrift.io/articles/archive/unit-testing-umbraco-plausible/
http://skrift.io/articles/archive/unit-testing-umbraco-with-umbraco-context-mock/
https://www.youtube.com/watch?v=1xS002NyGnc
I think it will be enough to start doing it.

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 Injection and loading dependent assembly in .NET

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.

How do I "White Label" my ASP.Net MVC Application?

I have a "white labelled" application that is installed onto multiple customers' servers. On any given installation the differences will include content, style sheets and graphics but also some actual code / business logic. I want my TFS Server to build all flavours of my application automatically. What are my options for doing this? e.g. should I be using Themes? What about #if conditional compilation flags.
P.S. The question is not about how to setup the Build Server - I've done that already.
For the business logic I would abstract the differences into a separate libraries, and then you can use an IoC / DI pattern or provider pattern to resolve the correct business logic at runtime.
As for the content I would look into themes. Essentially you could have your build server build all the code once, then when you package the code you choose which assemblies you need and use the appropriate configuration, and choose the appropiate theme folder for the client at hand.
I don't like using # directives in this case. If you think about it your unit tests would have to run for each conditional you have. If you remove the conditionals and abstract the differences your unit tests can just run on all the pluggable assemblies at once.
Content/image - you can make your own HtmlHelper/UrlHelper extension to do Html\Url.Content() to pickup right things for right customers, in addition to copying needed files from right folders (which is simple, /Content + /ContentCustomer1, 2, ...).
There's no single answer, I suppose. One easy answer would be to move your Order.Calculate() method to a partial class, so that you have
OrderPartsForCustomer1.cs
OrderPartsForCustomer2.cs
where you'll have
public partial class Order
{
public Money Calculate()
{
}
}
You'll just include needed .cs classes then, and don't clutter your code with #ifs.
If you want common code for all, and overrides just for specific customers, you can have OrderPartsCommon.cs, which you will copy/use if there's not customer-specific overide.

Resources