How to avoid Cyclic Dependencies when using Dependency Injection? - c#

I am relatively new to the concept dependency injection, so I am unsure about how it prevents cyclic dependencies. Let's say I have followed projects (the sample project structure might not be good but please bear with me)
Project A:
Domain Layer
IRepository
Project B:
RepositoryImpl --> implement IRepository interface
In this case Project B will need to reference Project A. But to set up Project A, let's say Unity Container, Project A will need to reference Project B in order to have something like this in the Unity Config.
container.RegisterType<IRepository, Repository>();
But doesn't this introduce cyclic dependency? Or is it I'm having wrong understanding in either Dependency Injection or cyclic Dependency? or even both?

You are missing an important concept here, which is the concept of the Composition Root. The best and most elaborate description of what a Composition Root is, can be found here. To summarize:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
As the article explains:
Most classes use Constructor Injection. By doing this they push the responsibility of the creation of their dependencies up to their consumer. That consumer -again- push the responsibility of the creation of its dependencies up as well.
We can’t delay the creation of our classes indefinitely. There must be a location where we create our object graphs. You should concentrate this creation into a single area of your application. This place is called the Composition Root.
Only the application's entry point contains a Composition Root, any other libraries in application do not.
This means that the Domain Layer itself does not register its types into the DI Container—only the startup project does this. When you do this, the Domain Layer will therefore not have to depend the Data Access Library (your Project B).
Both the first edition (chapter 2) and second edition (chapter 3) of the book Dependency Injection in .NET contain a elaborate discussion of an example that is very close to the application structure given in your question. The previously referenced Composition Root article is an excerpt from the second edition. The first chapter can be read for free online.

Related

Modern Layered Architecture Implementation

I recently finished reading Dino Esposito's great book Modern Web Development, and in it he addresses a suggestion for a Domain Driven Layered Architecture for web applications. I have always struggled with a specific piece of suggestions I have seen similar to the one below:
Specifically with reference to the IoC being made in the Infrastructure layer. I understand the reasoning behind this and it makes sense to me however how do you adequately implement that within the bounds of the ASP.NET MVC framework? To add a dependency resolver you need to implement the IDependencyResolver interface which exists in the System.Web.MVC namespace.
In past projects I would typically implement my IoC within the MVC application itself in the startup folder however this seems to be at odds with the suggestion for the layout.
I do not want to turn this into an opinion type of question, all I am looking for is a possible, actual concrete way to implement this pattern without dragging the System.Web.MVC namespace down to the infrastructure layer.
EDIT
To add a follow on diagram for the suggested architecture, and the part that is still confusing to me, it would appear that Dino's suggestion does indeed put the IoC container in the infrastructure assembly:
Answer to Your Question
Fundamentally, your question is "I am looking for is a possible, actual concrete way to implement this pattern without dragging the System.Web.MVC namespace down to the infrastructure layer"
There is a way to do this, and it involves introducing a new IoC container library, one dedicated for the purpose.
IDependencyResolver does not have to be your system wide resolution interface - it is just the interface used by MvC. There are other IoC containers, and a number of them provide adaptors to inject an implementation of IDependencyResolver that wraps their IoC logic.
This permits a few things:
The MvC components that depend on the ability to perform an explicit resolution can still depend on IDependencyResolver
Other layers in the system can depend on a different resolution interface, and thus contain a reference to an isolated fit-for-purpose assembly
Both the MvC layer and the other layers will all be accessing the same set of dependency/implementation registrations
Some examples of IoC containers that support this:
Autofac - with Autofac Mvc Support
You can see the last line of the sample is:
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
After that line, any MvC component that depends on IDependencyResolver will automatically get the AutofacDependencyResolver which wraps calls to the Autofac container
StructureMap - StructureMap.Mvc
Here is a comparison of a large number of c# IoC containers that may help you select the one that's right for you.
[Actual Implementation Concerns - aka My Opinion about Why this is NOT a good idea]
Your practice in your past projects of only using the IoC in the Mvc application is more correct, in my opinion, so the below concepts may already be familiar to you, but as you are considering referencing the IoC from the domain, I thought it worth exploring.
First question - Why?
While that answer provides a way to do what you're asking, based on that diagram, I confess it's not clear to me what the purpose is of depending on the IoC resolver from the domain layer, and why you would need to do that.
If you find yourself doing that, you may be accidentally using the Service Location Anti-Pattern
As outlined in that blog, there is no need to depend on the IoC resolver (or locator) - simply depend on the service you need, and let the IoC inject the appropriate implementation.
Part of the problem in understanding the intent is the diagram itself - it often happens that people draw diagrams by dropping on some boxes and connecting them up - without ever being clear about what the lines mean. Are they chains of dependency? Are they sequence of execution? What does it mean to have a line from the domain model box to the actual label of the infrastructure layer??? Is it depending on nothing? Or illustrative of a possible dependency that is not articulated here?
What should use the IoC resolver?
The only part of the system that should directly reference the IoC resolver is the composition root, which is effectively the entry point to the application. The first part 'wires up the object graph' - really, it registers how to resolve all possible dependencies from the interfaces that are depended on, to appropriate concrete implementations.
It then resolves the entry point object (or registers an IDependencyResolver so Mvc can resolve the entry point object, aka a controller). When the entry object is resolved, it automatically resolves all it's dependencies, in the process resolving next layer of dependencies, and so on all the way until you reach classes with no dependencies. Which is likely to be your domain layer, if you are doing DDD.
Dependency-less Domain Layer and the Onion Architecture
Since you are interested in DDD, the received wisdom is that the domain layer should not depend on anything that is not defined in the domain layer. If there is really a need to utilise the services of an infrastructure component such as a repository, use separated interfaces and put the interface in the domain layer, but the implementation in a concrete persistence layer.
The architectural pattern this lends itself to is known as the Onion Architecture also known as the Hexagonal Architecture
Using Other IoC Containers
While I don't think it's necessary to reference the IoC resolver/locator from the domain layer (or any layer, really), I do still think there is value in adopting a separate dedicated IoC container library, as outlined above.
The value is in some of the more flexible options for how to configure services, including some nifty convention based auto-configuration.
The one reason it might be worth depending on the IoC library in the domain layer is to co-locate the registration and configuration logic with the services that are being configured, which can help structure and organise your IoC dependency registrations. But just because you take a dependency on the IoC assembly to permit structuring your registrations, doesn't mean you should use the IoC resolver/locator.

Should I separate IoC binding seperation by project

I am new at domain driven design architecture. My project solution is like this:
Presentation(Web)
ApplicationLayer
QueryLayer
QueryHandlerLayer
DataLayer
I read from articles theese separations is doing to isolate jobs.
Presentation project references ApplicationLayer
But does not reference QueryLayer,QueryHandlerLayer and DataLayer.
But I am using IoC container and bind types to interface.
container.Bind(data interfaces).To(data classes);
container.Bind(query interfaces).To(query classes);
I can do this on PresentationLayer. But now all projects will be add reference to presentation layer.
Is this an issue about architecture? Or May I separated IoC container binding for all layers?
Using DI is about composing applications. An application might have multiple layers, but they are still part of the same application and must be composed together.
The appropriate place to compose an application is in the composition root, which should be as close to the entry point of the application as possible.
There are basically 3 common recommendations for composing applications with multiple layers, and all of them are perfectly acceptable.
Don't separate the layers into physical assemblies.
Compose the application in the presentation layer, and reference all other layers from the presentation layer.
Create a separate composition layer that references all of the other layers.
For the 3rd option, you should keep in mind that the composition layer is supposed to drive, not be driven by, the rest of the application.
See this answer for the reasoning behind this referencing and why it is important that you do reference every library from the composition root to avoid tight coupling. Or, as mentioned, you could use late binding to compose your application without referencing the assemblies directly, provided your deployment script copies over the DLLs.
I think the biggest thing I have learnt in recent usage is that at the fundamental level, DI is about Injecting Dependancies. That's a pretty redundant description, so let me elaborate:
DI starts with design. Everything should have what it needs provided to it via a constructor, or factory of some sort. This is where Interfaces are your best friend. Once you have done this, most of the work is done. Assuming some of the projects are shared, you have now delegated out all of the work to whoever is using it. This is probably old news, however.
Next, if you are in control of the container, consider creating a default module, which in the case of Ninject is a, NinjectModule. Create one of these for each application layer. This will form the "instructions" so to speak, for the container at the highest level of your program to put all the pieces together.
This can all be loaded by reflection trickery of which there is plenty of information around, like this.
Then it is as simple as loading all of these binding "instruction manuals" into the composition root (usually in the application) and you're good to go.

caliburn.micro, Bootstrapper and CompositionRoot

I'm trying to understand what CompositionRoot is about.
Right up to now I never found a deep description of what it is about,
only short statements of what shall not be done.
Is the Bootstrapper that comes along when leveraging caliburn.micro already that what is meant "CompositionRoot"?
Or is it closer to the servicelocator antipattern, as it can deliver merely anything that is inside the assembly and it's dependencies.
If someone has a good description of CompositionRoot, please share.
I already know the ploeh blog.
If I see that CompositionRoot leads to better architecture and / or helps me solve problems, I'm still willing to buy the book. But right know there is not enough
information around for me to see what it will help.
update
Let's pretend that all of my ViewModels get an EventAggregator injected (constructor injection). Now I want to dynamically create those ViewModels when they are needed.
I can register types beforehand (in the CompositionRoot), but how would I resolve dependencies later? As far as I understand, the Container should not be touched after the composition root. Definitly I do not want to create all instances before I need them (that would make the application start slow). Is "Register - Resolve - Release" meant here?
(that pattern is coined in the ploeh blog, too)
I assume you've seen Mark's article at http://blog.ploeh.dk/2011/07/28/CompositionRoot.
As it states:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
And that this should be:
As close as possible to the application's entry point.
In the case of Caliburn.Micro, the Bootstrapper class provides a ConfigureContainer method for you to override and compose you modules.
Ideally, it will only be your composition root that has a reference to your IoC container.
Caliburn.Micro will resolve your shell view model (if you use the generic version of the Bootstrapper) via your container.
It does also supply a static IoC class which is an implementation of the Service Locator (anti) pattern if you do need to reference the container outside of your composition root.
Update
If you wish to resolve types via your container at runtime after your composition root (for example if you have complex dependency chains) then use factory types.
These factory types would also have a reference to your IoC container. You could either:
Pass a reference to your container as a dependency to the factory type
Use the Service Locator pattern in your factories (e.g. the Caliburn.Micro IoC class)
Some IoC containers such as Castle Windsor and (using an extension) Ninject will generate factory types for you based on a factory interface and conventions (this is the nicest option)

Can I register all IoC container components in single layer, or each layer where used?

I'm using the Unity IoC framework and have a Bootstrapper.cs class in my host MVC layer to register all components. However in my architecture I have a 'services' layer below the MVC layer, that too uses DI and there are repository interfaces injected into it (repository interfaces are not used in the MVC layer - it has the services layer Interface injected into its Controllers).
So my question is the following: can I still register the repository interface to it's concrete type in the MVC/UI layer for the entire app, or do I add another reference to Unity and create another Bootstrapper.cs class in my 'services' layer to define Interface types for that that specific layer uses?
Even if the answer is I can register the Interface in the UI layer, I'd still like to know the common practice too. The thing I don't like about registering that type in the MVC/UI layer is I would have to add a reference to the Repository layer just to make the registration, even know it is not used in that layer. It's used in the services layer.
Thanks!
Each application should have its own Composition Root, the place where you configure the application (see this answer for details).
It depends on the context, but generally speaking, if you split your container configuration among the layers you are going to make decisions about the configuration of your layers too close to the layers and you'are likely to lose the general view.
For example, in one of your business logic layers you'are registering a service:
container.RegisterType<ISercice1, MyImplementation1>(new PerThreadLifetime())
But when using that layer in a web application you could decide that a PerSession or PerRequest lifetime would be better lifetimes. This decisions should be in only one place and not spread through the layers.
I turn your question on its head.
If you add a reference to Unity in your class libraries, you would have added dependencies to the framework you are using. That is quite the opposite of what you are trying to achieve.
The only adaptation your classes should need is to support constructors or using public properties - on interfaces. That's it!
So your application entry point should do all the 'bootstrapping'.
Note that a entry point could be different applications, as well as different test projects. They could have different configurations and mocking scenarios.
If your bootstrap.cs gets large, you could split it up into smaller parts for readability reasons. But I reject the idea of classes having any knowledge about the fact that they are being bootstrapped/moqed/injected and by what.
Consider re-use. Your current libraries is using Unity. They may be used in a project using StructureMap. Or why not Ninject.
In short, yes it is possible to keep the configuration at the top of the process or localized to each module. However, all dependencies must be resolved for the entire object graph in the process.
Localizing the configuration by keeping it in each module (assembly) is often a good idea because you are allowing your service layer to take responsibility for its own configuration. My answer to this question, IMHO, is a good practice.
Yes, application should have one composition root at entry point. But it can be a good practice to keep registrations of a classes inside a layer where they are implemented. Then pull these registrations from layers at composition root, registering implementations layer by layer. This is why:
Registration within layer can be redefined in other place, for
example at entry point. Most of IoC libraries work in such a way
that registration done later erases the registration done earlier.
So registration within layer defines just a default behavior which
can be easily overridden.
You don't need to reference IoC library in all your projects\layers, even if you have registrations defined inside these
layers. A very simple set of wrapper classes will allow you to
abstract away from IoC specifics anywhere except your entry point.
When your application has several entry points, reusable registration will greatly help to prevent repeating the same
registration. This copy\paste is always bad. And applications have
several entry points quite often. For example, consider the scenario
of cross-platform application having a separate entry point for
every platform it targets. Or business logic reused in web site and
in background process.
With reusable registration, you can build a very effective testing system. You will be able to run a whole layer from tests,
mock whole layers in automated way, and do it very effectively,
minimizing efforts on writing tests.
See my blog article illustrating these points in more detail, with a working sample.

Not understanding where to create IoC Containers in system architecture

Say I have the following 4 .net assemblies:
Winforms UI
Business Logic
SQL Server Data Access (implementing an IRepository)
Common Interfaces (definition of IRepository etc.)
My business logic (2) makes calls to the data access layer (3) through IRepository (defined in 4) using constructor dependency injection. However when I ceate a business object I need to pass in an actual repository. I do this by having a singleton class in my business logic layer return the currently in use concrete object implementing IRepository. I am coming to the conclusion that this is a bad thing, as my business logic layer now has to reference 3 as well as 4.
I think I need a IoC Container but the question is where I create/put it as it seems that wherever I create this (1 - UI)? will also need to hold a reference to 3 (SQL Server Data Access). Am I not just moving the problem rather than achieving actual decoupling?
Do I create the IoC Container in the UI. Or expose it through another new assembly.
(I'm using C#, .net 3.5 and AutoFac)
Thanks.
IoC container generally should be created in the host project (application entry point). For the Windows.Forms application that's the exe project.
Generally in simple solutions (under 10 projects), only a host project should have a reference to IoC library.
PS: Structuring .NET Applications with Autofac IoC
When registering components there are several possibilities:
Registration in code:
directly
Problem: you have to reference everything ( you are here)
indirectly
Problem : to find out what has to be registered
Solution:
use attributes
use marker interface as IService
use conventions (see StructureMap)
Registration with configuration file:
let the container do everything
read the file yourself
Top level is a way to go (UI, as Rinat said).
Now as for references, simplest way is just to go over all assemblies in the current folder and use some convention to get the services out. Attributes work fine, putting registrar classes in each assembly works fine, whatever suits you. The code for extracting everything should probably be in a separate assembly, unless your IoC framework already does that.
The module distinction and the "scopes" defined by the modules exist mostly at compile-time. In the run-time it's all one big mess ;) This is used by most IOC containers and they don't really care about where they are located. The IoC container for a web-app will typically be created at the outermost level (very close to the web-container itself).
It's true that you could create it anywhere, but I'd introduce an extra layer, let's call it 3.5.
Your current 3 would be where your IoC resides for Data Access - this would become a wrapper for your actual DAL. Based on your config, 3 would create either a mock repository or a concrete one.
So 2 still references 3, but it's just an interface to the actual DAL which is configured through your IoC framework.
Alternatively, you could roll your own 'el-cheapo' IoC - change your Big Ugly Singleton to a Static Gateway - Abstracting IoC Container Behind a Singleton - Doing it wrong?

Categories