Dependency Injection in .NET
About This Book
Dependency Injection in .NET introduces DI and provides a practical guide for applying it in .NET applications. The book presents the core patterns in plain C#, so you'll fully understand how DI works. Then you'll learn to integrate DI with standard Microsoft technologies like ASP.NET MVC, and to use DI frameworks like StructureMap, Castle Windsor, and Unity. By the end of the book, you'll be comfortable applying this powerful technique in your everyday .NET development.
This book is written for C# developers. No previous experience with DI or DI frameworks is required.
Purchase of the print book comes with an offer of a free PDF, ePub, and Kindle eBook from Manning. Also available is all code from the book.
Winner of 2013 Jolt Awards: The Best Books--one of five notable books every serious programmer should read.
Summary
Dependency Injection in .NET, winner of the 2013 Jolt Awards for Productivity, presents core DI patterns in plain C#, so you'll fully understand how DI works, covers integration with standard Microsoft technologies like ASP.NET MVC, and teaches you to use DI frameworks like Structure Map, Castle Windsor, and Unity.
About the Technology
Dependency Injection is a great way to reduce tight coupling between software components. Instead of hard-coding dependencies, such as specifying a database driver, you inject a list of services that a component may need. The services are then connected by a third party. This technique enables you to better manage future changes and other complexity in your software.
What's Inside
- Many C#-based examples
- A catalog of DI patterns and anti-patterns
- Using both Microsoft and open source DI frameworks
Also Mark Seemann's Dependency Injection in .NET book is a good place to start. Well written and has a chapter on Castle Windsor specifically.
They also have some good tutorials on code project, I used before:
UPDATE
Well, the most simplistic tutorial would be as follows:
1) In VS2010 create new console application
2) Right click on "References", select "Manage NuGet Packages", install Castle.Windsor
3) Use code below for Program.cs:
I think that reading the book "Dependency Injection in .NET" by Mark Seemann is the best way. Mark goes through several containers and is very good at all of them. http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1326500032&sr=8-1
I don't think that IOCBattle.com tells someone enough about real world use and best practices to rule out Ninject and Castle because they were much slower according to the results by MartinF who is the author of a little known IOC container.
Ninject is very easy to use and is in the Apress MVC 3 book. Unity is becoming popular as it is from Microsoft, and StructureMap is pretty nice (and has been favorable to many developers). They seem to perform pretty well. Unless someone with a heavy hit site has exposure to bench marking performance on each container or has done performance and load testing with concurrent users with a tool like JMeter.
I don't think some of these benchmarks accurately reflect the product. If your company must use the Microsoft stack, then hands down you must use Unity ( MEF lacks too many features for most situations). If you are "allowed" to use 3rd party / open source, then StructureMap, Ninject, Castle, and Autofac are the most popular. Again, Mark's book on DI has charts that break down which ones have auto-registration, xml configuration, lifetime.., this stuff becomes pretty important for an application.
This is a blog post on Composition roots or what you call entry points. Its from Mark Seemann the author of Dependency Injection in .NET. If you are looking for a deep understanding of DI this book is a must read.
There are a lot of samples out there on how to combine WCF and DI. If you are hosting your services in IIS you would need to write a custom ServiceHostFactory where you initialize you DI container. This is a sample for Microsoft's Unity.
As to
Do you use poor man's DI and pass all your references around through all your layers? Then you should definitely consider using a DI/IoC container like StructureMap, Castle Windsor, AutoFac or Unity.
If you are asking "how can I in general avoid the situation that someone does not follow my layer boundaries": Write tests that fail if an assembly references another one it should not reference (e.g. UI should not reference DAL).
UPDATE
I assume you wanted the service to use ICustomerBiz instead of the ICustomerRepository. If that is right the setup for Unity would look like this:
That depends on your needs for the IOC, but it is possible to use MEF as your IOC.
Glenn Block has a blog post about this from 2009.
http://codebetter.com/glennblock/2009/08/16/should-i-use-mef-for-my-general-ioc-needs/
Mark Seeman has a chapter on MEF as IOC in his book.
http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501/ref=sr_1_1?ie=UTF8&qid=1332021360&sr=8-1
Dependency Injection is a pattern. The pattern by itself does not use any memory. However, you can't create loosely coupled code when implementing static classes, so during runtime class instances should be created. The amount of memory this consumes however is negligible compared to all other parts of the system, especially in a web application where ASP.NET itself creates a lot of garbage per request. And in the very rare case that you are under very tight memory constraints (which will hardly never be an ASP.NET web application), you can build up object graphs that consist of only singletons. This means objects are created once and cached, and this can reduce the amount of garbage your application creates to zero. So the use of Dependency Injection itself doesn't have to consume more memory and the difference is negligible.
That doesn't mean that a tool such as Unity consumes some memory. I've hardly ever seen this been a problem, although its always possible that misuse of the tool causes memory leaks. I think you should profile the application before deciding to remove some tool that might not be the problem at all.
However, one common pitfall is that Entity Framework's
DbContext
is kept alive too long (longer than a single request). If you do that, you will typically hit lots of problems, such as concurrency bugs and memory leaks. This however is not strictly related to Dependency Injection, it's rather easy to accidentally cache aDbContext
for too long.This is a whole topic of its own. Dependency Injection is about applying the SOLID principles, especially the Dependency Inversion Principle. The Dependency Inversion Principle is about creating loosely coupled code. When done right, this increases the maintainability of a system. Complete books are writen about this subject.
Unity is just one of the many tools to use when using Dependency Injection, but for a really small application, you could even consider applying DI without any tool. For small applications there is a clear advantage in not using such tool.
But in general, where DI—as a pattern—helps in making your application maintainable, a DI library (such as Unity) will help in making your Composition Root (the place where you wire everything together) more maintainable.
Instead of reverting back to your old practices, I think you and your team should take a step back and see this as an opportunity to start learning something new and improve your skills. There is a reason that people apply the Dependency Inversion Principle, the SOLID principles and apply Dependency Injection. It's because these practices improve the overall structure of an application and makes a system as a whole more maintainable.
It does take some time, however, to understand and master the concept of Dependency Injection, but IMO its time worth spent. You will improve your skills as a developer, which makes you more valuable for your company and any other company if you decide to switch jobs.
The most influential work on the subject of Dependency Injection, is Mark Seemann's book Dependency Injection in .NET. That book has had a major impact on how I and many others write code. A second edition of that book is coming out in 2018. I'm co-authoring this new edition. My advice would be to read either one of these editions, and preferably the second, since it is a major upgrade.
Your question is fair enough. Resolving dependencies at runtime, based on some user input or configuration settings, is a well-known problem. Mark Seemann devotes separate section of his great book Dependency Injection in .NET to this problem - "6.1 Mapping runtime values to abstractions". And I can't fully agree with NightOwl888 that this is not a DI problem.
There are 2 main solutions for this problem.
First one, described by Mark Seeman in his book, is to have the factory that takes indication of selected implementation as parameter. Here is basic description how it works.
First of all, you should pass somehow which implementation you want to use. It could be just a string (e.g. "gmail", "yahoo"), but it's better to do it via
enum
:Then you should define the factory itself. In common, it will look like this:
Then you should provide implementation for the factory. It could be as simple as:
However, in more complex cases, instances of
IEmailSender
should also be created via DI container. In this case you could use factory based onIUnityContainer
:Then you should adjust
EmailSender
and injectIEmailSenderFactory
in it.Send()
method should be extended with value ofEmailTarget
enum that specifies selected sender:The last thing is proper composition root:
And finally when you need to send e-mail:
The second approach is more simple. It doesn't use the factory and is based on Unity named dependencies. With this approach your classes could be left as is. Here is the composition root:
Sender is created in the following way:
It's up to you to decide which of these approaches to use. Purists will say that the first one is better because you don't mix specific DI container with your application logic. Actually you do, if the factory is based on DI container, but it's concentrated in one place and could be easily replaced. The second approach is however much simpler and could be used for simplest scenarios.
Mark Seemann said in his book Dependency Injection in .NET, "creating an object instance is something the .Net Framework does extremely fast. any performance bottleneck your application may have will appear in other place, so don't worry about it."
Please note that Dbcontext enables lazy loading by default. Just by instantiating it, it doesn't have much impact on the performance. So, I would not worry about Dbcontext.
However, if you have some custom classes doing heavy lifting inside constructor, then you might want to consider refactoring those.
If you really want to compare the performance, you could wrap those dependencies with Lazy, and see how much performance you gain. Does .net core dependency injection support Lazy.
About testability
Due to the use of singletons and static classes MyViewModel isn't testable. Unit testing is about isolation. If you want to unit test some class (for example, MyViewModel) you need to be able to substitute its dependencies by test double (usually stub or mock). This ability comes only when you provide seams in your code. One of the best techniques used to provide seams is Dependency Injection. The best resource for learning DI is this book from Mark Seemann (Dependency Injection in .NET).
You can't easily substitute calls of static members. So if you use many static members then your design isn't perfect.
Of course, you can use unconstrained isolation framework such as Typemock Isolator, JustMock or Microsoft Fakes to fake static method calls but it costs money and it doesn't push you to better design. These frameworks are great for creating test harness for legacy code.
About design
About testing framework
You can use any unit testing framework you like. Even MSTest, but personally I don't recommend it. NUnit and xUnit.net are MUCH better.
Further reading
Sample (using MvvmLight, NUnit and NSubstitute)
Edit, the dependency always "exists" but it was moved outside of the class notice that
IMyServices
can now be defined in the same project asHomeController
whenMyService
is in totally another class. and your DLL withHomeController
can compile without knowing about yourMyService
dll effectivly decoupling them.this is a very complex topic and you should read a book about it. reading blogs videos and so on didn;t really help.
this is a good book. http://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/dp/1935182501
this is a great vidoe lecture series first 5 videos are about DI in general http://channel9.msdn.com/Blogs/mtaulty/Prism--Silverlight-Part-1-Taking-Sketched-Code-Towards-Unity
initilization is focused in a COMPOSITION ROOT http://blog.ploeh.dk/2011/07/28/CompositionRoot/
and the pattern you shown here is CONSTRUCTOR INJECTION
https://softwareengineering.stackexchange.com/questions/177649/what-is-constructor-injection
In addition to what Paul T Davies and Magnus Backeus have said. I think that at the end of the day it would be a people and cultural issue. If people are open minded and willing to learn it will be relatively easy to convince them. If they consider you a 'junior' (which is a bad sign because the only thing that matters is what you say not how old/experienced you are) you can appeal to a 'higher authority':
Stored procedures are dead and you are not the only one who thinks so:
There is no point in convincing people that are not willing to improve and learn. Even if you manage to win one argument and squeeze in NHibernate, for example, they may end up writing the same tightly coupled, untestable, data-or-linq-oriented code as they did before. DDD is hard and it will require changing a lot of assumptions, hurt egos etc. Depending on the size of the company it may be a constant battle that is not worth starting.
Driving Technical Change is the book that might help you to deal with these issues. It includes several behavior stereotypes that you may encounter:
Good luck!
Without modifing class
A
code you won't be able to UT theReadBlock
method using moq. You'll be able to UT this method using code weaving tools(MsFakes, Typemock Isolator and etc...)For example(MsFackes):
In side the
using
scope you'll be able to override any method CloudBlockBlob has, through the propertyAllInstances
.In the next section I'm going to discuss all the other options you have...
Option 1:
Since you create a new instance each time call
ReadBlock
(your method current behavior...), you better inject a factory instead of wrapper andDoSomething
should becreate
; Option 2:However based on your question and your comments it seems that your class 'has a dependency' instead of 'need a dependency'.
(Mark Siemens wrote a great book about DI, this chart was taken from his book)
With this new piece of inforamtion you method should be something like; Option 3:
But you don't want to change the signeture of the method:
Add
InternalsVisibleToAttribute
, then verify the behavior of the internal method.By reading between the lines, it feels to me that your class is a kind of "legacy code", by saying "legacy code" I mean class that do the job, won't change and verifying his behavior might be a waste of time. In the past I've posted a chart(in this answer) which may help you to decide the way to handle this case.
Mocking means that you develop your software components (classes) in a way that any class with behaviour is used/consumed/called-upon as an interface (or abstract class). You program to an abstraction. Run-time you use something (service locator, DI container, factory, ...) to retrieve/create those instances.
The most common way is to use construction injection. Here is an excellent explanation of why one would use DI, and examples of how to do it.
In your case, your component that uses the Entity Framework (your repository for instance) must implement a repository-interface, and any class that uses your repository should use it as an interface.
This way, you can mock the repository in your unittests. Which means that you create a unit-test-repository class (which has nothing to do with any database or EF), and use that when you create the instance of the class that you want to unit-test.
Hopefully this helps. There are many source to be found. Personally I just read this book and I found it to be very good. This is the authors blog.
Funny you should ask to have it explained like you were six years old; here's an explanation like you were five years old :)
Frankly, I think the reason for that is that most people actually don't understand what Dependency Injection is, which means that instead of grasping the concept of Inversion of Control, they go looking for a replacement for the
new
keyword they're already used to. Then they find a DI Container and (mis)use it as a Service Locator. Unfortunately, that's very easy to do.This is the reason why, in my book, I explain all the DI concepts without coupling the explanation to any single DI Container. That's actually the majority of the book.
Service Locator and Dependency Injection are two fundamentally different attempts at achieving loose coupling. Service Locator has many disadvantages, and offers no advantages not also offered by DI. This is why I think it's safe to call Service Locator an anti-pattern.
You don't need a DI Container to use DI; in fact, I would say that unless you take a rather sophisticated approach, it's probably better to avoid one.
I believe you are referring the following code -
It is normal for UI Project to reference other projects, and register dependencies in IoC container, because Composition Root should be placed as close to the application's entry point as possible.
If you instantiate UserService using new keyword in UI, they become tightly coupled - a change in one class forces a change in another.
IoC container solves the dependencies issue by resolving dependencies at runtime and pass them as needed.
If you want to know more about DI, you might want to read Dependency Injection in .NET by Mark Seemann and Adaptive Code via C# by Gary McLean Hall
I have struggled with the same question for quite some time. I habe make the experience that you usually do not need a ServiceLocator (btw: best description of this anti pattern here and what you can do to avoid it in the corresponding, very awsome, book).
Please the refactoring of your code below. The basic idea here is that you have just one root object that acts as the composition root (
Program
) and all child dependencies of the complex object graph below that root are automatically resolved by the container.Seem like Lookup class itself is a Service Locator Pattern.
Service Locator has few problems. One of them is it doesn't follow Don't call us, we'll call you principle. It directly ask for the things we need rather than handed them to us.
With the service locator, we have to examine the code, searching for capricious calls that retrieve a required service. Constructor injection allowed us to view dependencies—all of them—with a glance at the constructor, or at a distance, via IntelliSense.
Solution
Ideally, you want to inject
IRepository<Table001>
toMyClass
. I also use the similar approach in my projects.If you see yourself injecting a lot of dependencies into a single class, it might be that the class violates Single Responsibility Principle. You might want to separate it to different classes.
And I am looking forward to read this book about DI in .Net:
http://www.amazon.com/gp/product/1935182501/ref=ox_sc_act_title_3?ie=UTF8&m=ATVPDKIKX0DER
The only thing you should NOT inject are stable, 3rd party libraries that you know for sure won't change and don't need Testability, Maintainability, Parallel Development, Extensibility or Late Binding.
If the
StaticClass
actually contains the logic ofMyController
why not include it's methods as part ofStaticClass
? Otherwise, it must be doing something else, on another level (different concern).I'm sure you already have this excellent resource on your shelf, but just to be sure, I'll put a link here: Dependency Injection in .NET (Mark Seemann).
From my own personal experience: If you're actually making a small application, just for the fun of it and which you'll probably throw out when it's done, just have fun with it. Use Dependency Injection here and there, write some Unit Test to see how it feels and get the hang of it. You can't make if perfect. For example, can you easily change between a Console and WPF/WinForms application? What would need to change? How easily can you swap the modules between the two applications? Try writing different
ILog
implementations. Maybe you want your logs on your console, maybe you want them in some GUI, txt or xml file. How easy is to change your code? Loosely-coupled code is the whole point and the Dependency Injection pattern helps here.One way to handle those is to refactor towards Aggregates (or Facades). Mark Seemann wrote a good article on it, check it out (actually I highly recommend his book as well, just saying). So say you have the following (as taken from the article):
You can refactor it to:
Where
OrderCollector
is a facade (it wraps the previous 3 dependencies):I hope this helps.
EDIT
In terms of the cross-cutting concerns (logging and caching for example) and a strategy to handle them, here is a suggestion (that's what I usually do), say you have the following:
Here I'd use the decorator pattern to create an OrderService that has logging enabled:
It might look like a bit of overhead but IMHO, it's clean and testable.
Another way would be to go into Aspect Oriented Programming and look into concepts such as interception, where basically you intercept certain method calls and perform tasks as a result. Many DI frameworks (I wanna say all?) support interception, so that might be something that you prefer.