This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Which C#/.NET Dependency Injection frameworks are worth looking into?
Yes I know this question has been asked many times, but the various frameworks keep evolving, so I would like a fresh answer on the subject.
A few thoughts about the framework, they are not necessary black or white, but rather my preferences.
Things I like:
Convention based registrations
Constructor injection
Can also target Silverlight
Small footprint
One assembly
Fast
Thing I don't like:
Xml
Custom attributes
Service locator pattern
Things I don't think about:
Linq
Opensource
Sounds like you might want to try NInject.
It has a definite focus on being easy to use with little configuration overhead (no bulky XML config files, etc). It even comes with a nice, shiny, fluent interface to make things understandable.
autofac
Ninject
When you're not familiar yet with any of the big DI frameworks, you might consider the very easy SimpleServiceLocator (shameless plug). Let's compare it to your check list:
Constructor injection, check!
Can also target Silverlight, check!
Small footprint, check!
One assembly, nope 2. It needs the Common Service Locator.
Fast, double check!
No Xml, check! Only code based configuration is supported.
No Custom attributes, check! It is completely attribute free.
No Service locator pattern, check. Despite its name, you can do DI with it (just look at the examples on the site).
Open source, check! MIT License.
The idea behind the Simple Service Locator is:
to provide .NET application developers
with a inversion of control (IoC)
framework that is truly easy to use,
while allowing developers to replace
it with a more feature-rich IoC
framework when needed.
The Simple Service Locator is an
implementation of the Common Service
Locator library. The Common Service
Locator is a shared interface for
inversion of control and dependency
injection which application and
framework developers can reference.
Related
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.
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.
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 .
I am currently writing an open source SDK for a program that I use and I'm using an IoC container internally(NInject) to wire up all my internal dependencies.
I have some objects that are marked as internal so that I don't crowd the public API as they are only used internally and shouldn't been seen by the user, stuff like factories and other objects. The problem that I'm having is that NInject can't create internal objects which means that I have to mark all my internal objects public which crowds up the public API.
My question is: Is there someway to get around this problem or am I doing it all wrong?
PS. I have thought about using InternalsVisiableTo attribute but I feel like that is a bit of a smell.
Quick look at the other answers: it doesn't seem like you are doing something so different that there is something fundamentally wrong with Ninject that you would need to modify it or replace it. In many cases, you can't "go straight for [the] internals" because they rely upon unresolved dependency injection; hence the usage of Ninject in the first place. Also it sounds like you already do have an internal set of interfaces which is why the question was posed.
Thoughts: one problem with using Ninject directly in your SDK or library is that then your users will have to use Ninject in their code. This probably isn't an issue for you because it is your IoC choice so you were going to use it anyway. What if they want to use another IoC container, then now they effectively have two running duplicating efforts. Worse yet what if they want to use Ninject v2 and you've used v1.5 then that really complicates the situation.
Best case: if you can refactor your classes such that they get everything they need through Dependency Injection then this is the cleanest because the library code doesn't need any IoC container. The app can wire up the dependencies and it just flows. This isn't always possible though, as sometimes the library classes need to create instances which have dependencies that you can't resolve through injection.
Suggestion: The CommonServiceLocator (and the Ninject adapter for it) were specifically designed for this situation (libraries with dependencies). You code against the CommonServiceLocator and then the application specifies which DI/IoC actually backs the interface.
It is a bit of a pain in that now you have to have Ninject and the CommonServiceLocator in your app, but the CommonServiceLocator is quite lightweight. Your SDK/library code only uses the CommonServiceLocator which is fairly clean.
I guess you don't even need that. IoC is for public stuff. Go straight for internals.
But - that's just my intuition...
Create a secondary, internal API which is different from the external API. You may need to do the split manually...
I'm going to vote for the InternalsVisibleTo solution. Totally not a smell, really. The point of the attribute is to enable the sort of behavior you are wanting, so rather than jumping through all sorts of elaborate hoops to make things work without it, just use the functionality provided by the framework for solving this particular problem.
I would also suggest, if you want to hide your choice of container from the user, using ILMerge to combine the Ninject assemblies with your SDK assembly, and apply the /internalize argument to change the visibility of the Ninject assemblies to internal, so the Ninject namespaces don't leak out of your library (sorry, couldn't find a link to the ILMerge docs online, but there is a doc file in the download). There is also this nice blog post about integrating ILMerge into your build process.
You can
modify Ninject
pick a different container
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.