Dependency injection, composition root, and entry points - dependency-injection

I've spent a lot of time reading these articles (along with many others):
Mark Seemann - Pure DI
Mark Seemann - When to use a DI Container
Mark Seemann - Compose object graphs with confidence
Mark Seemann - Don't call the container; it'll call you
Mark Seemann - Understanding the Composition Root
and I'm still trying to wrap my head around DI and the concept of "wiring up the dependencies" and the "auto wiring" functionality of an IoC container.
I think I understand the theory of Dependency Injection and Inversion of Control and I've implemented the example shown here from 2016 (I updated the code to use PSR-11 and eliminate the need for the container-interop package):
https://www.sitepoint.com/how-to-build-your-own-dependency-injection-container/
The application of the container example is shown at the GitHub link: https://github.com/sitepoint-editors/Container .
Note that while this example uses PHP, I'm trying to understand the details of DI independently from language, so any language is welcome.
Can someone explain the difference between manually wiring up dependencies, and using a container's auto wiring functionality? The SitePoint article briefly mentions that more advanced containers add the automatic wiring functionality, implying that the example doesn't contain this function already. Can someone explain the application shown on the GitHub page and how that relates to core DI and IoC concepts, like the Composition Root.

Can someone explain the difference between manually wiring up dependencies, and using a container's auto wiring functionality?
Pure DI is the practice of applying DI without using a DI Container. This means that you build a graph of objects by newing up objects using the new construct of your programming language. See for instance this example in C# (from listing 12.2 of Mark's book Dependency Injection Principles, Practices, and Patterns):
new HomeController(
new ProductService(
new SqlProductRepository(
new CommerceContext(connectionString)),
new AspNetUserContextAdapter()));
According to that book, Auto-Wiring is:
the ability to automatically compose an object graph from maps between Abstractions and concrete types by making use of type information supplied by the compiler and the [runtime environment]. (see 12.1.2)
In other words, with a DI Container, you will be able to 'just' tell the container about your types, and it will figure out which dependencies a type has and will be able to 'wire' that type with its dependencies.
Considering the previous example, listing 12.3 shows how you only have to specify the mappings between abstractions and concrete types in a container:
var container = new AutoWireContainer();
container.Register(typeof(IUserContext), typeof(AspNetUserContextAdapter));
container.Register(typeof(IProductRepository), typeof(SqlProductRepository));
container.Register(typeof(IProductService), typeof(ProductService));
container.Register(typeof(CommerceContext), () => new CommerceContext(connectionString));
And when you ask for a HomeController, the container knows how to construct the entire graph.
The SitePoint article briefly mentions that more advanced containers add the automatic wiring functionality
To me, Auto-Wiring is what makes a library into a DI Container. Something can't be called a DI Container if it doesn't, at the very least, support Auto-Wiring.

Related

Spring definition of "Inversion of Control" vs Wikipedia definition - why exactly DI is a form of IoC (in terms of control flow)?

Wiki on Inversion of Control:
In IoC, custom-written portions of a computer program receive the
flow of control from a generic framework. A software architecture
with this design inverts control as compared to traditional procedural
programming: in traditional programming, the custom code that
expresses the purpose of the program calls into reusable libraries to
take care of generic tasks, but with inversion of control, it is the
framework that calls into the custom, or task-specific, code.
Spring's ApplicationContext is called IoC container.
When I write in my main() / some method ApplicationContext ctx = new ClasspathXmlApplicationContext(config.xml); MyCls cl = ctx.getBean("name"); I manage control-flow myself. Where is "Inversion of Control" in Wikipedia's terms? I call what I need myself(!), not some (Spring?) framework gives me any callbacks for me to fill with my code.
Spring uses "Inversion of Control" as exact synonym for "Dependency injection" and Wikipedia's article is about something else?
But here is Wiki on "Dependency injection" :
The "injection" refers to the passing of a dependency (a service)
into the object (a client) that would use it. Passing the service to
the client, rather than allowing a client to build or find the
service, is the fundamental requirement of the pattern. Dependency
injection is one form of the broader technique of inversion of
control. The client delegates the responsibility of providing its
dependencies to external code (the injector). the client only needs to
know about the intrinsic interfaces of the services because these
define how the client may use the services. This separates the
responsibilities of use and construction."
Given the above I don't understand how dependency injection can be a form of Inversion of Control, especially in terms of (inversion of) control flow.
This answer (Inversion of Control vs Dependency Injection) is related, but it is not an answer to this question, neither does it directly address control flow question.
P.S. My guess is that I need to look from the "reference frame" of the object itself - then normal control flow is when this code (=this object, its methods) creates new objects (dependencies) itself, and inverted control flow when somebody calls methods of that object passing already created objects-dependencies into it. Then that somebody (just my own code in main()) is like a magical framework and the code inside that object is like code within a call-back method. Just such a mental view of the process.
There's a lot of confusion about the terminology in this space, but what some people call IoC I call Dependency Injection (DI), exactly for the reason that Inversion of Control is a much broader concept.
When applying DI to a code base, however, you're not supposed to write MyCls cl = ctx.getBean("name"); outside of your Composition Root. This means that most of your code should just use the Constructor Injection pattern, like this:
public class MyCls {
public MyCls(MyDependency dep) {
// Assign dep to a class field here...
// That makes dep available to all method of MyCls.
}
}
This inverts the control in the sense that MyCls never gets to control MyDependency. This enables the composing code to share instances of MyDependency if that's desired, or create a new instance for each consuming class, if that's safer. Which option is best often depends on implementation details of the concrete class that implements the polymorphic dependency. Following the Liskov Subtitution Principle, the consuming class (MyCls) should have no knowledge of the implementation details of its dependencies, including which lifetime is best. Inverting control over dependencies nicely addresses that sort of issue.
I've tried to provide detailed descriptions, as well as a consistent pattern language, in my book on DI. While I'm a C# developer, I've learned a lot from many books that have examples in Java, so I've tried to perform the reverse manoeuvre and written a book with examples in C# (but on .NET Core so that it compiles on both Linux, Mac, and Windows) that should also be readable for Java developers.

How to implement Dependency Injection with MVC5 and MEF2 (Convention-Based) in an n-tier application?

I'm starting a new MVC project and have (almost) decided to give the Repository Pattern and Dependency Injection a go. It has taken a while to sift through the variations but I came up with the following structure for my application:
Presentation Layer: ASP.Net MVC front end (views/controllers, etc.)
Services Layer (Business Layer, if you prefer): interfaces and DTOs.
Data Layer: interface implementations and Entity Framework classes.
They are 3 separate projects in my solution. The Presentation Layer only has a reference to the Services Layer. The Data Layer also only has a reference to the Services Layer - so this is basically following Domain Driven Design.
The point of structuring things in this fashion is for separation of concerns, loose-coupling and testability. I'm happy to take advice on improvements if any of this is unreasonable?
The part I am having difficulty with is injecting an interface-implementing object from the Data Layer into the Presentation Layer, which is only aware of the interfaces in the Services Layer. This seems to be exactly what DI is for, and IoC frameworks (allegedly!) make this easier, so I thought I'd try MEF2. But of the dozens of articles and questions and answers I've read over the last few days, nothing seems to actually address this in a way that fits my structure. Almost all are deprecated and/or are simple console application examples that have all the interfaces and classes in the same assembly, knowing all about one another and entirely defying the point of loose-coupling and DI. I have also seen others that require the Data Layer dll being put in the presentation layer bin folder and configuring other classes to look there - again hampering the idea of loose-coupling.
There are some solutions that explore attribute-based registration, but that has supposedly been superseded by Convention-Based registration. I also see a lot of examples injecting an object into a controller constructor, which introduces it's own set of problems to solve. I'm not convinced the controller should know about this actually, and would rather have the object injected into the model, but there may be reasons for this as so many examples seem to follow that path. I haven't looked too deeply into this yet as I'm still stuck trying to get the Data Layer object up into the Presentation Layer anywhere at all.
I believe one of my main problems is not understanding in which layer the various MEF2 things need to go, since every example I've found only uses one layer. There are containers and registrations and catalogues and exporting and importing configurations, and I've been unable to figure out exactly where all this code should go.
The irony is that modern design patterns are supposed to abstract complexity and simplify our task, but I'd be half finished by now if I'd have just referenced the DAL from the PL and got to work on the actual functionality of the application. I'd really appreciate it if someone could say, 'Yep, I get what you're doing but you're missing xyz. What you need to do is abc'.
Thanks.
Yep, I get what you're doing (more or less) but (as far as I can tell) you're missing a) the separation of contracts and implementation types into their own projects/assemblies and b) a concept for configuring the DI-container, i.e. configure which implementations shall be used for the interfaces.
There are unlimited ways of dealing with this, so what I give you is my personal best practice. I've been working that way for quite a bit now and am still happy with it, so I consider it worth sharing.
a. Always have to projects: MyNamespace.Something and MyNamespace.Something.Contracts
In general, for DI, I have two assemblies: One for contracts which holds only interfaces and one for the implementation of these interfaces. In your case, I would probably have five assemblies: Presentation.dll, Services.dll, Services.Contracts.dll, DataAccess.dll and DataAccess.Contracts.dll.
(Another valid option is to put all contracts in one assembly, lets call it Commons.dll)
Obviously, DataAccess.dll references DataAccess.Contracts.dll, as the classes inside DataAccess.dll implement the interfaces inside DataAccess.Contracts.dll. Same for Services.dll and Services.Contracts.dll.
No, the decoupling part: Presentation references Services.Contracts and Data.Contracts. Services references Data.Contracts. As you see, there is no dependency to concrete implementations. This is, what the whole DI thing is about. If you decide to exchange your data access layer, you can swap DataAccess.dll while DataAccess.Contracts.dll stays the same. None of your othe assemblies reference DataAccess.dll directly, so there are no broken links, version conflicts, etc. If this is not clear, try to draw a little dependency diagram. You will see, that there are no arrows pointing to any assemblies whioch don't have .Contracts in their name.
Does this make sense to you? Please ask, if there is something unclear.
b. Choose how to configure the container
You can choose between explicit configuration (XML, etc.), attribute based configuration and convention based registration. While the former is a pain for obvious reasons, I am a fan of the second. I think it is more readable and easy to debug than convention based config, but that is a matter of taste.
Of course, the container kind of bundles all the dependencies, which you have spared in your application architecture. To make clear what I mean, consider a XML config for your case: It will contain 'links' to all of the implementation assemblies DataAccess.dll, .... Still, this doesn't undermine the idea of decoupling. It is clear, that you need to modify the configuration, when an implementation assembly is exchanged.
However, working with attribute or convention based configs, you generally work with the autodiscovery mechanisms you mention: 'Search in all assemblies located in xyz'. This does require to place all assemblies in the applications bin directory. There is nothing wrong about it, as the code needs to be somewhere, right?
What do you gain? Consider you've deployed your application and decide to swap the DataAccess layer. Say, you've chosen convention based config of your DI container. What you can do now is to open a new project in VS, reference the existing DataAccess.Contracts.dll and implement all the interfaces in whatever way you like, as long as you follow the conventions. Then you build the library, call it DataAccess.dll and copy and paste it to your original application's program folder, replacing the old DataAccess.dll. Done, you've swapped the whole implementation without any of the other assemblies even noticing.
I think, you get the idea. It really is a tradeoff, using IoC and DI. I highly recommend to be pragmatic in your design decisions. Don't interface everything, it just gets messy. Decide for yourself, where DI and IoC really makes sense and don't get too influenced by the community's religious discussions. Still, used wisely, IoC and DI are really, really, really powerful!
Well I've spent a couple more days on this (which is now around a week in total) and made little further progress. I am fairly sure I had the container set up correctly with my conventions discovering the correct parts to be mapped etc., but I couldn't figure out what seemed to be the missing link to get the controller DI to activate - I constantly received the error message stating that I hadn't provided a parameterless constructor. So I'm done with it.
I did, however, manage to move forward with my structure and intention to use DI with an IoC. If anyone hits the same wall I did and wants an alternative solution: ditch MEF 2 and go with Unity. The latest version (3.5 at time of writing) has discovery by convention baked in and just works like a treat out of the box - it even has a fairly thorough manual with worked examples. There are other IoC frameworks, but I chose Unity since it's MS supported and fares well in performance benchmarks. Install the bootstrapper package from NuGet and most of the work is done for you. In the end I only had to write one line of code to map my entire DAL (they even create a stub for you so you know where to insert it):
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().Where(t => t.Namespace == "xxx.DAL.Repository"),
WithMappings.FromMatchingInterface,
WithName.Default);

Dependecy Injection Library Agnostic Code using a Common Wrapper class?

Is anyone aware of a set of classes to abstract away the specific Dependency injection library (Spring, Castle, StructureMap, Ninject... etc.) ?
We all use a DI container to abstract away a specific implementation of our code, but we could also use the same interface / strategy pattern to write a generic interface based DI container using specific implementations such as Castle.Windsor, Unity... etc.
In general the basic pattern of "Getting and Object" from a container is pretty universal. For example:
IService service = IocContainer.Get<IService>();
Where IocContainer is a generic wrapper class around a specific library implementation such as Castle.Windsor, Unity... etc.
Of course in addition to writing specific implementations that you could 'plug-in' and of course, each implementation would have its own configuration file format.
Anyone have suggestions on existing well tested wrapper classes for DI containers?
The problem with all these wrappers and container abstractions is that they restrict you to the common subset of the functionallity that all the containers share. That's why you shouldn't do it. Instead use the container of your choice correctly:
Have just one "Get" in your application - in the composition root
Configure the container with conventions rather than usein a one by one service registration. This makes the configuration small.
Use factory interfaces wherever you have to create instances after the initial composition of your application and implement them as part of the container configuration (Some container do this implementation automatically for you)
With these simple rules your container is known in one place only - the composition root - which makes any abstraction of the container obsolete. That way you can use the full power of the container.

How does Unity (et al) actually help with Dependency Injection

I have some questions about DI containers (Unity in particular) and how they actually aid in DI.
I believe I understand IoC/DI and have been using constructor based DI for some years. Usually with my use of DI it involved simply having a constructor on my class, say MyClassX that takes an interface as an argument say IDataService and then using the new operator to create an instance of an IDataService implementing class and pass it into MyClassX's constructor. This way MyClassX doesn't need to know the exact type of the IDataService it is using decoupling it from a specific type. Now correct me if I am wrong, but that's what I understand DI to be...though it does not have to be constructor based.
Now I have seen a stack of examples of Unity on the net, but I am finding it difficult to not only understand everything it does (it seems like a magic object factory to me) but also how it exactly aids in DI as I understand it. To me Unity seems more like a Factory implementation (or a Mock framework?) rather than anything to do specifically with DI. I think I have really missed something though and am waiting for an "ah ha" moment. I have done alot of Googling but examples don't help... I need an theoretical explanation.
Can someone explain to me what Unity is exactly for...the broad points of what it does and how it is related to DI as I understand it.
Your understanding of basic Dependency Injection is correct. Constructor injection is the most common pattern.
Some other DI Unity does:
Lifetime management – instance creation can be singleton, one per
thread, and other advanced models.
Handles dependency graphs - request a root object and Unity creates all its dependency’s
dependencies.
Enables method and property injection – requires a
Unity attribute in your business code (which I prefer to avoid)
Service locator pattern – generally considered an anti-pattern
1 and 2 are nice when you need them. I think #3 and #4 are to be avoided when possible because it adds dependencies in your code to your Unity container.
The big bang that you are missing is Aspect Oriented Programing enabled by Interception with Unity. This allows the implementation of cross cutting concerns. Logging is the classic example. If you want more, start reading all the Enterprise Library Call Handlers for exception handling, validation, etc. or just start searching the web for AOP.
When you combine constructor injection of dependencies with external implementation of cross cutting concerns, you can get very close to business objects that only contain business logic. In a large Enterprise development team, that’s a very big bang.
When the object graph is simple you may not see the obvious advantages of using a DI container.
Say you have a class MyClassX which depends on IExampleA, IExampleB. Now the Implementation of IExampleA and IExampleB may depend on some other classes and so on. Now, this kind of object graph is complex to handle manually when it comes to materialized/instantiate it.
This is where DI comes into play. Once registered(class and its depended classes), All you need to do is,
var myclassX = _container.Resolve<MyClassX>()
And, don't get me wrong here, DI can provide much more than just resolving dependency. For example managing the LifeStyle and LifeCycle of objects etc.

Binding to multiple concrete implementations with IOC frameworks?

I'm relatively familiar with the concepts of DI/IOC containers having worked on projects previously where their use were already in place. However, for this new project, there is no existing framework and I'm having to pick one.
Long story short, there are some scenarios where we'll be configuring several implementations for a given interface. Glancing around the web, it seems like using any of the mainstream frameworks to selectively bind to one of the implementations is quite simple.
There are however contexts where we'll need to run ALL the configured implementations. I've scoured all the IOC tagged posts here and I'm trying to pour through documentation of the major frameworks (so far looking at Unity, Ninject, and Windsor), but docs are often sparse and I've not the time to inspect source for all the packages.
So, are there any mainstream IOC containers that will allow me to bind to all the configured concrete types for one of my services?
One thing that caught me the first time I was trying to resolve all implementations of a registered type was that un-named (default) type registrations will not be returned when you call ResolveAll(). Only named instances are returned.
So:
IUnityContainer container = new UnityContainer();
container.RegisterType<IMyInterface, MyFirstClass>();
container.RegisterType<IMyInterface, MySecondClass>("Two");
container.RegisterType<IMyInterface, MyThirdClass>("Three");
var instances = container.ResolveAll<IMyInterface>();
Assert.AreEqual(2, instances.Count, "MyFirstClass doesn't get constructed");
So I somehow missed this my first pass looking through Unity somehow...but I'll answer my own question.
Unity has precisely what I wanted.
http://msdn.microsoft.com/en-us/library/cc440943.aspx
Also, for anyone else doing the IOC hunt and dance like me, this link proved to be invaluable.
http://blog.ashmind.com/index.php/2008/09/08/comparing-net-di-ioc-frameworks-part-2/

Resources