Examples of IoC Containers [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Does anyone have good examples of IoC containers (preferably in c#) and how and why to use them ? I have checked out the wiki page and Ayende's example, but I don't quite get the concept yet.
And when and where should I use an IoC container ?

I've used StructureMap quite a bit. The rest of your question is pretty loaded. I'll try to explain the concept in an example.
Suppose you created a website that will accept payments through PayPal. PayPal is now a dependency. But you don't want to code against a specific PayPal provider.
Instead, you would create and code against an interface like this:
interface IPaymentProcessor
{
bool ProcessPayment(amount, ....);
}
All your PayPal code would reside in a class that implements the methods of your interface - PayPalPaymentProcessor, for example.
Now you have an object that you will actually use to process the payments. This could be a Controller (ASP.NET-MVC, ViewModel-WPF) or just a class as shown here:
class PaymentProcessor
{
private IPaymentProcessor _processor = null;
public PaymentProcessor(IPaymentProcessor processor)
{
_processor = processor;
}
public bool ProcessTransaction(Transaction trans)
{
_processor.ProcessPayment(trans.amount, ...);
}
}
This is where an IoC container comes in. Instead of you calling the constructor manually, you would let an IoC container inject the dependency:
PaymentProcessor processor = ObjectFactory.GetInstance<PaymentProcessor>();
This piece of code tells StructureMap "Anytime you see a constructor that needs an IPaymentProcessor, return a new PayPalPaymentProcessor".
ObjectFactory.Initialize(x =>
{
x.ForRequestedType<IPaymentProcessor>().TheDefaultIsConcreteType<PayPalPaymentProcessor>();
});
All this mapping is separate from your implementation code and you could swap out these at a later point with little refactoring needed. There is a lot more to IoC containers, but that the basic concept. You can automate the injection of constructors to avoid the calls directly to ObjectFactory as well.
Hope this helps!

Be aware of the following limitations of the IOC container. I have to warn people, because I am living with the hell of having to support a system using it:
Exceptions thrown by constructors get swallowed. You only get the “couldn’t create dependency” exception. That means you can't catch expected exceptions if it's throw in a constructor.
Can’t step through constructors.
Forgetting to register an interface breaks at runtime instead of compile time.
All your classes can only have one constructor and they all have to accept interfaces as parameters.
All dependencies are instantiated so you can’t share instances, which means your memory usage can get large quickly.
It promotes a lot of interdepencies which can hide the fact that you code has turned into spaghetti. Making it easier to instatiate all of these interdepencies just masks that there is a potential underlying problem.
You can't manage your own "Unit of Work" very easily because you can't manage a transaction across multiple dependencies since you didn't have control of instantiating them and passing in the context of that transaction.
Don't get me wrong, I love dependency injection and the inversion of control principle, but I think the IOC container could be used responsibly, but just be aware of the battles that you will need to fight because of the above list.

If you want to see an IoC container under the hood, and also the point (Dependency Injection), there's a great podcast on DNR TV (Episode 126) that really goes into detail about how to create them, why you'd need them. It's a really wonderful podcast. Once you've watched this video, you'll then be able to look at Unity,Ninject, StructureMap, etc and be able to understand what they're doing

Check out Spring IoC (.net) a java/.net container. The documentation is quite good introduction.
In a brief:
You can think about IoC as an architecture that encourage:
objects composition and programming to an interface.
This gives you the following:
the ability to unit test your code easily (you can easily test your objects in isolation by mocking up all its dependencies).
An extremely advance configuration (because your program with IoC is just bunch of objects and an configuration that glues the objects together).
The ability to extend or modify byte compiled application (this is true for Java I'm not sure if it is true for .net).

We use Ninject because of its simple API and fast resolution of objects. It's very well documented and leverages C# 3.0 features like lambda expressions to make specification easier.
You can find several screencasts on Ninject here

Are you trying to build a IoC container why not use one of the available ones like Spring.NET, StructureMap or Unity Application Block? Here is a list of open-source IoC projects

I normally use StructureMap - mostly because I'm familiar with the syntax. I've also heard good things about autofac and I'm looking forward to trying out Ninject when it hits v2.
You might want to take a look at this answer where I talk about a basic usage of an IoC container (I always think things are easier to understand with a simple example) - that might help you to understand things a little more. Basically, the IoC container helps you to build objects with all the dependencies satisfied, and allows you to change your dependencies with minimal configuration code.

Try reading Introduction to Unity Application Block and in ASP.NET StoreFront: Dependency Injection screencast you can see more about Dependency Injection concepts.

I am using Unity for my IoC container, but the difference between the containers resides in more than what you can do with DI.
DI (Dependency Injection) is mainly a way to get more loose coupling between disparate parts of your program. So, if you wrote a game that you like how it works, by using DI you can change the characters or physics engine in the game without changing other parts of the game, so, if someone pays more money they get the more realistic engine, or the better characters, but since nothing else is changing, the testing is simpler.
Unit testing is also easier with DI as you can mock out the database, for example, by just changing the implementation that will be used by the application, without affecting anything else.
If you use Spring.NET for example, you will get access to a very powerful framework, but it may do a great deal that you won't use, so look for something smaller. I think the best rule is to find the smallest, simplest implementation that meets your needs, and use that.

Related

Unity autowiring: to use or not to use?

seems like with the new unity version has been added support for autowiring.
How many of you are familiar with it and strngly suggest me to use or not use it? Seems to me that the use of it limit my control on the DI especially for what regard the unit tests, am I thinking wrong?
I'm assuming that this question is about Auto-Registration, since Unity has had Auto-Wiring for years.
Since I wrote my When to use a DI Container article a couple of years ago, I've only become slightly more radical in my attitude towards DI Containers. In that article, I describe the benefits and trade-offs of using DI Containers, as opposed to Poor Man's DI (manually composing code).
My order of preference is now:
Manually write the code of the Composition Root (Poor Man's DI). This may seem like a lot of trouble, but gives you the best possible feedback, as well as it's easier to understand than using a DI Container.
Use Auto-Registration (AKA Convention over Configuration). While you lose compile-time feedback, the mechanism might actually pull your code towards a greater deal of consistency, because as long as you follow the conventions, things 'just work'. However, this requires that the team is comfortable with the Auto-Registration API of the chosen DI Container, which, in my experience, isn't likely to be the case.
Only use Explicit Register if you have a very compelling reason to do so (and no: not thoroughly understanding DI is not a good reason). These days, I almost never do this, so it's difficult for me to come up with some good cases, but advanced lifetime management may be one motivation.
It's been 1½ years since I last used a DI Container in any production code.
In summary, and in an effort to answer the specific question about Unity:
Seriously consider not using Unity at all (or any other DI Container).
If you must use Unity, use the Auto-Registration feature. Otherwise, you're likely to get more trouble than benefits from it.
Caveat: I'm writing this as a general response, based on my experience with DI and various DI Containers, including Explicit Registration and Auto-Registration. While I have some knowledge about previous versions of Unity, I don't know anything about the Auto-Registration features of the new version of Unity.
I've built a container which automatically register your services. All you need to do is to tag them with an attribute.
this is not autowiring per se, but that's part of my point. Unity have from the start been able to build classes which has not been registered in the container. And that's imho a big weekness as the class might be used with dependencies that it shouldnt use or that it will have a different lifetime than intended.
My choice to use an attribute was to be able to make sure that all services can be resolved and built. When you call the builder.Build() method my container will throw an exception if something can't be resolved.
Hence you will directly at the startup see if something is missing, rather then later at runtime.
So autowiring might seem good, but as you say: You'll loose control only to discover it later during runtime if something is missing.

ASP.NET MVC3 Hand coding IoC

Ninject, Sprint.NET, Unity, Autofac, Castle.Windsor are all examples are IoC frameworks that are available. However, I like the learning curve and control of writing my own. It is definitely common practice to not "re-invent the wheel" and just use pre-existing structures. If your comment is along those lines please be gentle.
Can IoC be implemented without the use of XML? It seems to me most, if not all, of the aforementioned frameworks use XML but I would much rather just write mine in C# instead of using XML to load a .dll. The C# is all converted into one .dll eventually anyway.
From my understanding, if wrong please correct, IoC can be used with DI to make the functionality of classes be based off of their definition and implementation while allowing for a separation of concerns.
This is accomplished in C# using microsoft's library System.ComponentModel.IContainer by having a class which inherits it. A class, such as Product, would have an interface IProduct. A generic constructor would then inherit from IContainer and in the constructor, allow a repository to be passed in, an instantiated object to be passed in, and a function to be passed in. This would allow a controller action to then instantiate an interface (IProduct), instantiate the generic constructor with the current repository instance, and then pass it the interface and function.
Is this setup accurate?
I am still trying to learn more about this topic, and have read the wiki articles on IoC, DI, and read about Castle.Windsor, ninject, Unity, and looked over multiple definitions from the MSDN regarding C# libraries which are used. Any assistance, corrections, or suggestions, are greatly appreciated. Thanks
Can IoC be implemented without the use of XML?
Yes, Ninject, Unity, Castle Windsor and Autofac can be configured without using any XML at all. (not sure about Spring.NET, last time I used it it was impossible, version 1.3)
From my understanding, if wrong please correct, IoC can be used with
DI to make the functionality of classes be based off of their
definition and implementation while allowing for a separation of
concerns.
If under "IoC" you mean "IoC container" then yes, it can be used with DI, but since DI is a particular case of Inversion Of Control your IoC container will be just a container for you dependencies. By just having it your will not magically get any DI-friendly types. It's just a support for managing your inverted dependencies.
Edit
As Mystere Man pointed in his answer you need to improve you understanding of the IoC containers. So I would recommend to read this wonderful book (from Mark Seeman) about all that stuff.
I think it is a great exercise to start without a DI container. Before focusing on using a DI framework, focus on best patterns and practices. Especially, design all classes around Dependency Injection and make sure your code follows the SOLID principles. Both sounds pretty easy, but this takes a shift in mindset and a lot of practice before you will get this right (but is well worth it).
When you do this, and do this well, you will quickly notice that your application will evolve in amazing ways. Your code will be testable and extendable in ways that you never imagined before, without your code to rot over time (however, it keeps constant focus to prevent code from rotting).
Still, when you do all this right (which –again- takes a lot of practice), you will still have one part of your application that, despite your best efforts, will get more complex and harder to maintain, as the application grows. This is the part of the application where you wire all dependencies together: the Composition Root.
And this is where DI containers come in. They have fancy names and compete with each other over features, but their goal can be stated in a single sentence:
The goal of a DI container is to keep the Composition Root
maintainable.
Although you can write your own simple DI container to wire up your dependencies, to prevent your Composition Root to become a big fragile, ever changing ball of mud, the container must at least have one crucial feature: Automatic Constructor Injection (a.k.a. auto-wiring). With auto-wiring, the container will look at the constructor arguments of a type that it needs to create, and it will inject the dependencies in it based on the types of those arguments. This feature will make the difference between a maintenance nightmare and a healthy Composition Root. Although creating your own container that supports auto-wiring isn't that hard (with expression trees it takes about 20 lines of code), the moment you start needing auto-wiring is the time to start using one of the existing DI frameworks.
So in conclusion, if you feel it helps you in the learning experience by doing this by hand, please do, as long as you stick to SOLID, DI, DRY, and TDD. When the burden of changing your Composition Root for each change in the application gets too big (which will be sooner than you might expect), switch to an established framework.
I would suggest using an existing DI container first, to understand how it works from the end user perspective. Then you can go about re-designing the wheel. My favorite saying is "You have to know the rules before you can break them".
Some of what you've said doesn't make a lot of sense. you don't have to use System.ComponentModel.IContainer in any framekwork i know of. Maybe Unity requires that (Microsoft's container) but none of the others do. I'm not familiar with Unity thogh.

Can MEF on asp.net be used for Dependency Injection?

I know what Dependency Injection is in theory, but I haven't ever actually used Dependency Injection in any of my projects yet. So consider me to be a DI noob.
The straightforward question is; Can MEF be used for Dependency Injection?
If it can, my follow up question is; Is it a good idea to use MEF for dependency Injection?
I understand that my follow up question may be viewed as being subjective. But, I am looking for best practices and reasons for and against. So, I hope that my follow up question doesn't rustle too many feathers.
The context of all this is I feel a little lost trying to figure out how to make a plugin framework for asp.net mvc.
As I explain in my book MEF can be used as a DI Container, but in its current incarnation it's not particularly well-suited for the task.
MEF was designed to address extensibility scenarios, and while it has a lot of overlapping features, it's quite limited when it comes to configuration and lifetime management.
MEF can, I believe, be used for dependency injection; at least I use it in my own small home WPF project currently. I suspect it might get messy when you need to inject different types for an interface for different deployments of your application, if you require this. It would require going to some effort to add the right classes to your catalog.
Where I work, using ASP.NET MVC2, we use Castle Windsor for dependency injection. We make use then of the XML configuration to initialize the container. This means we can inject different types for an interface without having to rebuild.
I believe .NET offers another option to MEF, similarly called MAF. It's supposed to be more complex, but offer much more control. I don't however know anything more about it.
(I'm not very experienced (1 year employed), so if someone disagrees with my on something, they're probably more correct)
Glenn Block (former product manager of MEF) answered this FAQ in a blog post.
Most of the shortcomings of MEF mentioned in his post have been addressed by MEFContrib: it contains additional catalog and export provider implementations to add support for POCOs, open generics and interception.
update: the recently released MEF2 Preview3 adds support for open generics and attribute-less registration out of the box. The APIs of preview releases aren't final but this is a good indication that those features will be in the next (>v4.0) .NET release .

What is dependency injection and why would I want to use it? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is dependency injection?
Other developers on my team keep talking about dependency injection. I have looked it up on Wikipedia but I still don't understand exactly what it is or when I would want to use it in my designs. If you have any good examples of when you have used it or when you shouldn't that would really help me out. Thanks
The basic idea is that when an object needs some other other to do it's work (say for example, a database connection), instead of creating that object internally, the object is "injected" into the object, usually either as a constructor parameter, or by a public property that is set before the object is used.
The advantage of that is that the value of the used object can be changed externally (this is especially true if the object is declared as an interface). One common use of this is to replace concrete object with mock object for unit testing.
Another term of reference which might be of assistance is "Inversion of Control".
Rather than constructing your software with dependencies and assumptions about the libraries you will continue to use with that application forever, IoC or DI allow you to specify an interface which must be satisfied by some other component, then at runtime supply a mapping of interface-satisfying components for the executing application (usually in a service container which provides the IoC satisfying service as some variety of service-resolution service).
This abstraction allows you to more readily replace an implementation which no longer meets your organization's needs with a new version, or even an entirely new backing technology, with a smaller footprint of change and thus lower risk.
Castle Windsor is one .Net implementation of an IoC container.
You might find this article useful in understanding this whole idea.
The idea is to help you decouple your clases so that each individual class can be used or tested independently.
I find the dependency injection article from Misko Hevery very explanatory including great example (java). Have a look at the series of articles around the topic.

What is Castle Windsor, and why should I care?

I'm a long-time Windows developer, having cut my teeth on win32 and early COM. I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR. I'd never heard of Castle Windsor until I started participating in Stack Overflow. I've read the Castle Windsor "Getting Started" guide, but it's not clicking.
Teach this old dog new tricks, and tell me why I should be integrating Castle Windsor into my enterprise apps.
Castle Windsor is an inversion of control tool. There are others like it.
It can give you objects with pre-built and pre-wired dependencies right in there. An entire object graph created via reflection and configuration rather than the "new" operator.
Start here: http://tech.groups.yahoo.com/group/altdotnet/message/10434
Imagine you have an email sending class. EmailSender. Imagine you have another class WorkflowStepper. Inside WorkflowStepper you need to use EmailSender.
You could always say new EmailSender().Send(emailMessage);
but that - the use of new - creates a TIGHT COUPLING that is hard to change. (this is a tiny contrived example after all)
So what if, instead of newing this bad boy up inside WorkflowStepper, you just passed it into the constructor?
So then whoever called it had to new up the EmailSender.
new WorkflowStepper(emailSender).Step()
Imagine you have hundreds of these little classes that only have one responsibility (google SRP).. and you use a few of them in WorkflowStepper:
new WorkflowStepper(emailSender, alertRegistry, databaseConnection).Step()
Imagine not worrying about the details of EmailSender when you are writing WorkflowStepper or AlertRegistry
You just worry about the concern you are working with.
Imagine this whole graph (tree) of objects and dependencies gets wired up at RUN TIME, so that when you do this:
WorkflowStepper stepper = Container.Get<WorkflowStepper>();
you get a real deal WorkflowStepper with all the dependencies automatically filled in where you need them.
There is no new
It just happens - because it knows what needs what.
And you can write fewer defects with better designed, DRY code in a testable and repeatable way.
Mark Seemann wrote and excellent book on DI (Dependency Injection) which is a subset of IOC. He also compares a number of containers. I cannot recommend this book enough. The book's name is: "Dependency Injection in .Net" https://www.manning.com/books/dependency-injection-in-dot-net
I think IoC is a stepping stone in the right direction on the path towards greater productivity and enjoyment of development team (including PM, BA an BOs). It helps to establish a separation of concerns between developers and for testing. It gives peace of mind when architecting which allows for flexibility as frameworks may come in and out.
The best way to accomplish the goal that IoC (CW or Ninject etc..) takes a stab at is to eliminate politics #1 and #2 remove need for developers to put on the facade of false understanding when developing. Do these two solutions not seem related to IoC? They are :)
Castle Windsor is Dependency Injection container. It means with the help of this you can inject your dependencies and use them without creating them with the help of new keyword.
e.g. Consider you have written a repository or a service and you wish to use it at many places, you need to first register your service / repository and you can start using it after injecting it on the required place.
You can take a look at the below tutorial which I followed to learn castle windsor.
link.
Hope it will help you.
Put simply. Imagine you have some class buried in your code that needs a few simple config values to do its job. That means everything that creates an instance of that class needs to get those dependencies, so you usually end up having to refactor loads of classes along the way to just pass a bit of config down to where the instance gets created.
So either lots of classes are needlessly altered, you bunch the config values into one big config class which is also bad... or worst still go Service Locator!
IoC allows your class to get all its depencencies without that hassle, and manages lifetimes of instances more explicitly too.

Categories