Is there a layered approach to Dependency Injection / Inversion of Control - dependency-injection

DI/IOC: There are so many frameworks and the examples quickly get sticky with details particular to that framework. I find that I often learn a new technology best if I can learn its principles outside of a framework (the forest obscuring the trees).
My question: What are the simple principles of DI/IOC? I am looking for a (framework agnostic) building approach that outlines what is gained, what the options are, what the costs are, for each simple principle. Please don't just paste links unless they actually address my question. I keep getting lost in those forests ;}
Second question: Once I understand the core principles, would it be worth building my own simple framework? IE, would the insight gained be valuable relative to the effort expended?
Thanks in advance!
Robert

My very quick and dirty take on it
Dependency Injection and Inversion of Control are not the same thing. Inversion of Control uses DI.
IoC is a way of snapping your application together at run time rather than compile time.
Instead of 'newing up' a type in the code, it is injected at run time by the IoC container.
The IoC container knows what to inject into your class because a) It looks at the constructor of that class - all the parameters are interfaces. b) It looks at its configuration file and sees what classes that implement each interface you have chosen to represent that interface in your application.
Here's a very basic example
Let's say you have an interface IEmailer for sending emails:
public interface IEmailer
{
void SendEmail();
}
And you have at least one implementation of this interface:
public class IainsEmailer : IEmailer
{
public void SendEmail()
{
// Send email
}
}
You define in IoC container's config file (somehow):
IainsEmailer is my choice for IEmailer
Then in your code you can have the following and the IoC container will inject an IainsEmailer into any constructor that needs an IEmailer.
public class MyClass
{
private IEmailer _emailer;
public MyClass(IEmailer emailer)
{
_emailer = emailer
}
// You can now use emailer as if you have created it
_emailer.SendEmail();
}
I could go on. And on. But this really is the whole idea of IoC in a nutshell.

This is a somewhat dated but good overview Inversion of Control
To me the underlying principles that drive Ioc are the concepts of components, modularity, loose coupling, cohesion. This means that you design software that is broken up into cohesive, modular units with clear dependencies, or links to other units. This is a basic principle of engineering in any field, not just programming. Once you have modularity, to create a functional system you need a way to link these components so that they form a functional whole. IoC/DI frameworks are components that abstract this concept of linking, and allow you to write code that declares links between components, and then have the ability to execute these links. The "inversion" part comes from the fact that the components themselves no longer link to their dependencies, instead the linking is performed outside, by a linking component. This in turn, is called dependency injection. A typical IoC/DI framework allows you to write code that specifies a particular implementation of an interface that another component depends on, then allows you to instantiate that component and upon creation, the required implementation will be provided by the IoC container. This then abstracts the concept of object creation.

Your questions warrant a fully fledged Wikipedia article. I assume you've already read up on the actual article so here's my shorter take on your question: Dependency Injection is all about instantiation.
The main idea is that classes should not be responsible for instantiating their dependencies. The DI framework takes over instantiation because it can do it flexibly, via a configuration mechanism that is (typically) external to your code.
This enables you to write classes that are:
Decoupled from their dependencies.
Better focused on their actual responsibility (rather than on their dependencies)
Can be changed through configuration without the need for recompilation.
More easily testable.
Arguably, better designed.
To answer your second question: if you're trying to learn about DI then writing a framework yourself is clearly overkill. I would recommend that you choose one of the popular open source frameworks and write code that consumes it - most have good tutorials just for that purpose.
Taking it to the next level you can take the source code of the framework you were using and start digging into it. The good framework are very well written and relatively easy to read.
Good Luck!
urig
PS - If you're in .net, don't start with MEF. Start with Windsor, Unity or Spring.Net. MEF is both more and less than a DI framework so leave it for a little later.

Related

Implementing cross-cutting concepts into LOB/DI application

I am currently creating a small personal windows (desktop) .NET LOB application and I want to use the opportunity to increase my knowledge and experience with DI. I've separated my application into model, DAO and GUI parts but I am wondering how to implement some cross-cutting concepts such as:
currently logged on user - used for:
asserting rights - in some parts of the application I check if the user has necessary rights
auditing - recording user actions into a separate database table
etc
current application parameters (loaded from configuration file or table) - used for:
defining business strategy
defining UI (theme for example)
etc
logging to file/database log - used for:
logging UI actions (clicking on buttons etc.)
logging business processes (results of calculations, strategy decisions etc.)
logging infrastructure stuff (SQL used to for CRUD operations)
etc
At the moment I can think of several ways to provide this information:
Using static properties - UserEntity.Current, Configuration.Current, Logger.Current, etc.
Pros:
Simple to implement
Simple to use
Cons:
Gets messy
It is unclear which part of the application uses what
Can not be used if you need finer granularity (for example if for some processes in the application you need to override current values)
Using DI - giving each class which needs this information a property/ctor parameter
Pros:
It is clear for each class what it needs
It is easy to unit test
Cons:
It just seems to explode constructors
Makes problems if class needs to have a default constructors
Difficult to setup when classes get instantiated by 3rd party (XAML)
Using ServiceLocator
Pros:
Easy to setup
Easy to use
Cons:
It is unclear which part of the application uses what
Difficult to setup finer granularity (but not impossible)
I am currently leaning towards ServiceLocator as I've worked with it before and it worked quite nice. However I am concerned about loss of control. It gets very easy to just reach for the service locator instead of trying to fix a design problem.
Can somebody provide their experiences/knowledge?
Sounds like perfect case to start with aspect-oriented approach. Your application's LOB will be designed according to business functional requirements that has been cross-cutted with different non-functional requirements: authentication, audit, logging, etc.
In same time, some of current application requirements could be solved by dependency-injection. To start, I recommend first to identify composition root. For example, in wpf applications it’s the Application.OnStartup method. In case if you are able to identify composition root it is better to avoid service-locator. Service locator will add unneeded complexity while maintaining and testing, because it could resolve literally anything, thus dependency management will be complicated.
Next step, to decide: should dependency injection and aspect-oriented approaches be separated or combined. Both approaches has benefits and drawbacks.
While choosing separated approach you could use postsharp with a lot of benefits: great samples and documentation, community and ready to use aspects. But nothing come for free, postsharp has only limited number of features in free version and complicated integration with continues-integration.
Another solution: combine dependency-injection with dynamic-proxy. As long as you follow conception: program to an interface, not an implementation β€” you will achieve all requirements. Benefits: one place to wire all components. There are two major drawbacks: first dynamic proxy is quite limited itself, second β€” integration between dependency injection container and dynamic proxy β€” for some container it already exists, for others not. Example: Ninject extension Interception, or StructureMap and Interception.
I recommend you to take a look at following resources to find more answers yourself:
* Book AOP in .NET: Practical Aspect-Oriented Programming by Matthew D. Groves: first chapter available for free
* Book Dependency Injection in .NET by Mark Seemann: well-written book about dependency injection, and chapter #9 dedicated to interception, approach that I found quite useful in cases that you had described in question. Author of book also has an excellent blog dedicated to dependency injection and video about aspect-oriented programming with dependency Injection.

verifiying I understand the difference between IoC, Ioc Container, DI and service locator

read many posts about the difference between the 3 idioms. But got more confused, then I ran into this article:
http://martinfowler.com/articles/injection.html
just want to see if I got this right. please correct me if I'm wrong.
Please notify me of correction and additions:
IoC- is the concept of decoupling an application from the implementation of a service it uses. The application contain a ref to Iservice and is not incharge of instanciating the concrete service.
There are at least two way to achive so:
DI - The concrete service is injected as a ctor param/throw a setter/throw interface injection (what does the latter mean?)
ServiceLocator - is a component that knows all the concrete services the application may need. The application explicitly asks for the concrete service from the Locator.
*IoC container is actualy a controls' factory ("provider").
I got a bit confused by the "when to prefer (1) or (2)" part in the article. could someone please tell from his own experience in a layman words ?
"Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice."--> How is locator more straightforward ? because it uses method invocation explicitly ? What is it better to use DI when there are multiple applications?
IoC is the concept of decoupling an application from the implementation of a service it uses.
It is true that IoC goes hand in hand with decoupling interfaces from implementations, but I see it as a more general principle. This SO answer gives a very good explanation of the concept.
There are at least two way to achive so:
1) DI
2) ServiceLocator
I wouldn't say that the Service Locator pattern is an example of Inversion of Control. Quite the opposite - when you are using the Service Locator, you are acquiring the required dependencies in active way, nobody else does it for you (contrary to the DI, where the container handles the dependencies for you, you just have to give it a possibility of doing so - a setter, a constructor parameter or by implementing method of injection interface).
How is locator more straightforward ? because it uses method invocation explicitly?
I think that Martin Fowler is referring to the general idea of IoC that may make the code harder to understand if you've never seen the IoC/DI concept used before. On the other hand, the code using Service Locator to acquire some dependencies may be easier to grasp on first encounter.
What is it better to use DI when there are multiple applications?
When you are creating a component that is supposed to be reusable, the advantage of DI is that it doesn't make your component dependent on anything else than the original dependency (in MF's example, the MovieLister depends only on the MovieFinder interface when using DI).
Also, it is quite easy for others to use your component - the just have to pass the dependencies using the means of DI you provided.
When using the Service Locator, you also add dependency on the interface of the Service Locator itself. With segregated interface for the Locator, that may not be a problem. But it may also be harder for users of your component to satisfy the dependencies of your component, as MF writes:
The difference comes if the lister is a component that I'm providing to an application that other people are writing. In this case I don't know much about the APIs of the service locators that my customers are going to use. Each customer might have their own incompatible service locators.

Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)

I have a solution with two relevant (to this question) projects, and a few others;
Class library with functionality used by several other projects.
ASP.NET MVC application.
My question is basically where I should do IoC with Ninject 2, considering...
The class library needs some DI love, among other things in the repository classes which need web request specific session objects (think Unit of Work).
The MVC app needs DI since with Ninject 2 you basically inherit from NinjectHttpApplication.
Unit tests for the class library need to be aware of this to inject a different set of repositories.
Unit tests for the web app need to be injected for the same reason.
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
I can't do DI only in the class library since the MVC app needs to inherit from NinjectHttpApplication to begin with.
I can't do DI only in the MVC app - the class library is used by other libraries, after all, and the MVC app shouldn't know too much about the internals of the library anyway.
I guess this is the only way out I can see: Independent IoC for both projects. The class library and the MVC app each have their own IoC setup and do DI for their stuff without really caring about each other.
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
Thanks!
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.

IoC, AOP and more

What is an IoC container?
What is an IoC/DI framework?
Why do we need a framework for IoC/DI?
Is there any relationship between IoC/DI and AOP?
What is Spring.net/ninject with respect to IoC and AOP?
JMSA,
James Kovacs wrote a fantastic article which covers many of your questions I would recommend reading it Here
Spring.Net, Ninject, Unity, Castle Windsor, Autofac are all IOC containers which are configurable in different ways, many of them do also support AOP.
Frameworks for IOC/DI are useful because they provide standard mechanisms, for example if you are hiring a new developer it is much easier to say, we use this framework and pass them the links to the tutorials / help guide. At the same time these frameworks are tried and tested by a large community / companies.
Let me know if any of your questions remain unanswered after reading the article and the above answes and I'll do my best to provide further assistance.
From a semantics point of view...
Dependency Injection itself implies a dependency, i.e. something that is required for construction/use (the application's "core concerns"). For example, a car is not a car without an engine.
Aspects are described as being cross-cutting to the application's core concerns. That means both separate from and non-crucial to the core concerns (you could think of them as "nice-to-haves"). Since the application can run without aspects, are they really dependencies? For example, a car is still a car even without an immobiliser.
(Of course, this is from a theoretical standpoint. In the real world matters like security are often as crucial to the existence of a marketable product as the core concerns themselves.)
So in while in practice DI can be used to implement aspects, I would not call that process true DI. This is coming from someone who uses constructor injection exclusively.
Martin Fowler has a good article here on the meaning of Inversion of Control and Dependency Injection.
Spring.NET usage AOP is described in detail here. I'm more familiar with the Java-based version of Spring, so I cannot say with absolutely certainty that Spring.NET currently only supports proxy-based AOP.
That is, a class to be advised must implement an interface. Spring will create a dynamic proxy that implements this interface and delegates to the original target instance.
Although it does state:
In a future release we will implement proxies using inheritance, which will allow you to proxy classes without interfaces as well and will remove some of the remaining raw reference issues that cannot be solved using composition-based proxies.

Dependency Injection Frameworks: Why do I care?

I was reading over Injection by Hand and Ninjection (as well as Why use Ninject ). I encountered two pieces of confusion:
The inject by hand technique I am already familiar with, but I am not familiar with Ninjection, and thus am not sure how the complete program would work. Perhaps it would help to provide a complete program rather than, as is done on that page, showing a program broken up into pieces
I still don't really get how this makes things easier. I think I'm missing something important. I can kind of see how an injection framework would be helpful if you were creating a group of injections and then switching between two large groups all at once (this is useful for mocking, among other things), but I think there is more to it than that. But I'm not sure what. Or maybe I just need more examples of why this is exciting to drive home the point.
When injecting your dependencies without a DI framework you end up with arrow code all over your application telling classes how to build their dependencies.
public Contact()
: this(new DataGateWay())
{
}
But if you use something like Ninject, all the arrow code is in one spot making it easier to change a dependency for all the classes using it.
internal class ProductionModule : StandardModule
{
public override void Load()
{
Bind<IDataGateway>().To<DataGateWay>();
}
}
I still don't really get how this makes things easier. I think I'm missing something important.
Wouldn't it would be great if we only had to develop discrete components where each provided distinct functionality we could easily understand, re-use and maintain. Where we only worked on components.
What prevents us from doing so, is we need some infrastructure that can somehow combine and manage these components into a working application automatically. Infrastructure that does this is available to us - an IOC framework.
So an IOC framework isn't about managing dependencies or testing or configuration. Instead it is about managing complexity, by enabling you to only work and think about components.
It allows you to easily test your code by mocking the interfaces that you need for a particular code block. It also allows you to easily swap functionality without breaking other parts of the code.
It's all about cohesion and coupling.
You probably won't see the benefit on small projects, but once you get past small it becomes really apparent when you have to make changes to the system. It's a breeze when you've used DI.
I really like the autowiring aspect of some frameworks ... when you do not have to care about what your types need to be instantiated.
EDIT:
I read this article by Ayende # Rahien. And I really support his point.
Dependency injection using most frameworks can be configured at runtime, without requiring a recompile.
Dependency injection can get really interesting if you get your code to the point where there are very few dependencies in the code at all. Some dependency injection frameworks will allow you define your dependencies in a configuration file. This can be very useful if you need a really flexible piece of software that needs to be changed without modifying the code. For example, workflow software is a prime candidate for this type of solution.
Dependency Injection is essential for the Component Driven Development. The latter allows to build really complex applications in a much more efficient and reliable manner.
Also, it allows to separate common cross-cutting concerns cleanly from the other code (this results in more reusable and flexible codebase).
Related links:
Inversion of Control and Dependency Injection - Wiki
Component-Driven Development - Wiki
Cross-cutting concerns - Wiki

Resources