Why doesn't Simple Injector have an IContainer abstraction like Unity? - dependency-injection

I have used Unity for my last project and was generally pleased. But benchmarks have me thinking I may go with Simple Injector for my next project.
However, Simple Injector does not seem to have an interface for its Container class. This means that anytime I want to use the container in a method, I cannot mock the container for unit testing.
I am confused how a tool that really functions based of interfaces, would not itself make an interface to the container. I know that the classic methods of dependency injection do not need the container for anywhere more than the startup. (The rest uses constructor injection.) But I have found that when the rubber hits the road that cannot always be true. Sometimes you just need the container in order to do a "resolve" in the code.
If I go with Simple Injector then that code seems to gets harder to unit test.
Am I right? Or am I missing something?

Simple Injector does not contain an IContainer abstraction, because:
It would be useless for Simple Injector to define it,
because in case of depending on IContainer instead of Container, your code would in that case still depend on Simple Injector, and this causes a vendor lock-in, which Simple Injector tries to prevent.
Any code you write, apart from the application's Composition Root, should not depend on the container, nor on an abstraction over the container. Both are implementations of the Service Locator anti-pattern.
You should NOT use a DI library when unit testing. When unit testing, you should manually inject all fake or mock objects in the class under test. Using a container only complicates things. Perhaps you are using a container, because manually creating those classes is too cumbersome for you. This might indicate problems with your code (you might be violating the Single Responsibility Principle) or your tests (you might be missing a factory method to create the class under test).
You might use the container for your integration tests, but you
shouldn't have that many integration tests in the first place. The focus should be on unit tests and this should be easy when applying the dependency injection pattern. On top of that, there are better ways of hiding the container from your integration tests, compared to depending on a very wide library-defined interface.
It is trivial to define such interface (plus an adapter) yourself, which justifies not having it in the library. It is your job as application developer to define the right abstractions for your application as stated by the Dependency Inversion Principle. Libraries and frameworks that tend to do this will fail most of the time in providing an abstraction that works for everyone.
The library itself does not use that abstraction and a library should, according to the Framework Design Guidelines, in that case not define such abstraction for you. As stated in the previous point, Simple Injector would get the abstraction wrong anyway.
Last but not least, the Simple Injector container does actually implement System.IServiceProvider which is defined in mscorlib.dll and can be used for retrieving service objects.

I think the answer given here is entirely founded upon accepting that ServiceLocator is an anti-pattern, which in turn I don't believe is globally accepted as true. See Windows Workflow Foundation's Extensions support.
The anti-pattern link (and its two updates) may also be weak... the latest update claims violation of encapsulation ("relieving you of the burden of having to understand every implementation detail of every piece of code in your code base.") while then at the same time claiming that up-front knowledge of dependencies is somehow different for that claim than discovering them via unit tests. Either way, you're going to need to know what to give it.
All in all, if you want to follow the Locator pattern, either leverage its IServiceProvider, or simplify your container population (to a singleton) and create a static wrapper for it.

Related

Confused over using IOC container, service locator and factory

Suppose I have a BaseForm which depends on an ILogger or IResourceManager or something like that. Currently it resolves the correct implementation of the required service using the service locator which I know is an anti-pattern.
Is using the constructor injection the right way to resolve this kind of dependency?
Do I have to register my BaseForm (and its' derived types) in the container in order to create instances of them with resolved dependencies? Doesn't that complicate everything?
Is it bad to use a static factory wrapped around a service locator?
Unit-testing aside, will I really be punished because of using service locator anti-pattern?
Sorry about asking many questions at once. I've read the following SO questions and many others but reading them only added to my confusion:
How to use Dependency Injection and not Service Locator
What's the difference between the Dependency Injection and Service Locator patterns?
How to avoid Service Locator Anti-Pattern?
If possible, you should always go with dependency injection, since it has a few clear strength. With UI technologies however, it is not always possible to use dependency injection, since some UI technologies (in .NET space, Win Forms and Web Forms, for instance) only allow your UI classes (forms, pages, controls, etc) to have a default constructor. In that case you will have to fall back to something else, which is service locator.
In that case I can give you the following advice:
Only fall back to Service Locator for UI classes that can't be created by your container using dependency injection, and for stuff that you aren't unit testing anyway.
Try to implement as less logic as possible in those UI classes (as Humble objects with only view related stuff). This allows you to unit test as much as possible.
Wrap the container around a static method to hide the container from the rest of the application. Make sure that a call to this static method fails, when the dependency cannot be resolved.
Resolve all dependencies in the (default) constructor of that type. This allows the application to fail fast when one of its dependencies cannot be resolved when that type is created, instead of later on when some button is clicked.
Check during app start-up (or using a unit test), if all those UI types can be created. This saves you from having to go through the whole application (by opening all forms) to see if there is an error in the DI configuration.
When types cannot be built by the container, there is no reason to register them in the container. If they can be created by the container (such as with ASP.NET MVC Controller classes), it can be useful to register them explicitly, because some containers allow you to verify the configuration up front, which will detect configuration errors in those types right away.
Besides unit testing, there are two other important arguments against the use of the Service Locator, which are given by Mark Seemann in his famous blog post Service Locator is an Anti-Pattern:
Service Locator "hides a class’ dependencies, causing run-time errors instead of compile-time errors"
Service Locator is "making the code more difficult to maintain"

Using factories to create multiple objects when using Dependency Injection

I am trying to figure out how to create multiple objects when using Dependency Injection. As far as I understand the standard approach is to inject a Factory which is then used to create the objects. The part I struggle with is how the Factory creates the objects. So far I see two possible solutions:
The Factory just uses new() to create the object.
Isn't DI supposed to free me of the use of new for non value objects?
What happens if the Object to be created has dependencies that could be resolved by the IoC?
Use the Container as Serviclocator
solves the problems of just newing objects at the cost of introducing an antipattern or is it no longer an antipattern if the use of the serviclocater is constraind within the factories?
It feels like i can coose between a bad and a bad solution. Is there something I am missing or do I understand somthing wrong here?
Edit Currently I am not using an Ioc at all but thinking about Ninject. Although the Autofac DelegateFactories sound very promising.
For starters, I don't consider using a container as service locator in factories an anti-pattern. There are genuine circumstances where it is entirely appropriate. Come to think about it, container aware factories are really container extensions, and those seem to be excluded from service locator bashing. Even the most pure IoC frameworks like AutoFac or Ninject have extensive extension capabilities. A most typical use case for this pattern is resolving to different implementations based on where the service is used.
With regards to using new to create instances inside factories, that is acceptable as well. The IoC/DI message got a bit distorted there and never using new is really a side effect, rather than the goal of DI. The first imperative of Dependency Injection is to externalise creation of dependencies from the component. A factory satisfies that imperative as long as it itself gets injected into component. The questions you need to ask yourself when evaluating such scenarios are:
Does the component itself create its dependencies? A: No, the factory does.
Can you make the component work with different dependencies without modifying it? A: Yes, by injecting a different factory.
I said this before, IoC containers are just factories on steroids. For 80% use case they work out of the box. The other 20% might require tweaks of the above two varieties. I tend to use container aware factories when I want to create components that require both registered dependencies and some input at run-time and new-ing factories when I create Domain objects that don't have dependencies on other services, but take all their construction parameters at run time.
Although the interface for your factory will be defined at the application level, you would typically define the implementation of that factory class close to your DI configuration, thus as part of your composition root. Although calling the container directly from your code is an implementation of the Service Locator anti-pattern, any code that is defined inside the compostion root is merely mechanics and is therefore not Service Locator. As long as newing up objects or calling into the container is done inside (or very close to) the composition root, this is not a problem, because the application will still be clean from any locator / container.
In other words: use the factory approach. Whether or not you need to new up objects directly inside your factory or make use of the container, depends on the objects. Letting the container create the objects is preferable, especially when they got dependencies on their own, but not all objects can be created by the container. In that case you need to revert to the new operation. Both are fine when the code is part of the composition root and not of the application. The factory itself can have dependencies of its own. This should not be a problem. You can let the container wire-up the factory instance.

what's the point of Dependency Injection Frameworks?

I am sure that I am somewhat lost in this area... my understanding is that Dependency Injection means initializing something that is required by a class..so for instance.
If my controller is going to need a service and I want to be able to test it then I should define two Constructor methods for it... so, my question is... why do people use Frameworks to achieve this?? Im lost
public class CompaniesController : Controller
{
private ICompaniesService _service;
public CompaniesController()
{
_service = new CompaniesService();
}
public CompaniesController(ICompaniesService service)
{
_service = service;
}
A major reason is to better support unit testing and mocking out objects to create controlled tests.
By not specifying the implementation inside the class, you can 'inject' an implementation at run time. (In your example, the ICompaniesService interface).
At runtime, using an inversion of control/dependency injection container such as StructureMap, Unity or Castle Windsor, you can say "hey, anytime someone wants an instance of ICompaniesService give them a new CompaniesService object".
To unit test this class, you can mock our a ICompaniesService and supply it yourself to the constructor. This allows you to setup controlled methods on the mock object. If you couldn't do this, your unit tests for CompaniesController would be limited to using only the one implementation of your companies service, which could hit a live database etc, making your unit tests both slow and inconsistent.
People don't use a Dependency Injection Framework to generate the code that you provided in your example. That's still the work of the developer.
The Dependency Injection Framework is used when somebody calls the constructor. The Framework will Inject the concrete implementation of the ICompaniesService rather than the developer explicitly calling the constructor.
While it is a specific product, the nInject Homepage actually has some really good examples.
From Wikipedia:
Without the concept of dependency
injection, a consumer who needs a
particular service "ICompaniesService" in order to
accomplish a certain task would be
responsible for handling the
life-cycle (instantiating, opening and
closing streams, disposing, etc.) of
that service. Using the concept of
dependency injection, however, the
life-cycle of a service is handled by
a dependency provider/framework (typically a
container) rather than the consumer.
The consumer would thus only need a
reference to an implementation of the
service "ICompaniesService" that it needed in order to
accomplish the necessary task.
Read this one too:
What is dependency injection?
People use Dependency Injection frameworks because otherwise you have to write a metric ton of boring, repetitive factory classes (if using dependency injection, that is).
It can be done, it's just very, very annoying.
I think your understanding is only partly correct. Dependency Injection is "injecting"
a dependency of a component into it. Its a more specific form of inversion of control. During
this process some dependencies can also be initialized before injecting.
With DI, the onus of looking up the dependency is not on the component
(as in ServiceLoacator pattern) but upto the container in which the component is
running. The pattern has following advantages:
Dependency lookup code can be eliminated from the component.
Some frameworks providing auto-wiring, injecting saving you from manually creating your component
hierarchies (Answers one of your questions)
Allows you to interchange implementations of your dependencies. (without using Factories)
Testing (replacing dependencies with mock implementations)
In your code example, a dependency can be injected by a DI container at runtime via the second
constructor. Other forms of injections are also possible (depending on the DI container). e.g.
Field injection, setter injection, etc.
There's a good article by martin fowler who coined the DI term
You dont have to have a DI framework, but at some point in your codebase a concrete implementation is going to need to be instantiated and injected into your constructors/properties. It can get very messy if you dont have a DI framework, I recommend looking at Castle Windsor although as mentioned there are others that will perform the same functionality. Or if you could role your own....:)
I'll pitch in:
You can accomplish dependency injection simply by having a parameterized function definition.
However, in order to make that work consistently, everyone has to actually do that. Many find that's its easier to enforce the convention by using a factory design pattern.
Dependency injection frameworks solve the problem of reducing the boilerplate of writing those factories.
I would say that dependency injection through a factory, is non-ideal. In my opinion factories add an extra layer of indirection and in a sense make deterministic functions in-deterministic in the sense that they are now a function of the inputs, plus state from the rest of the program (your di setup) which you cannot see from the function definition alone. Factories make code harder as they add an extra layer of indirection I'd argue that in many cases it's really not too hard to follow the convention and manually inject classes via the function arguments. Again though, for a large codebase, it's probably easier to enforce the rule through a factory.
..that being said sometimes I do wonder if these large codebases would even be this large if they didn't write so many things which try to preemptively solve problems that they don't have in the first place.

Utility of IoC and Dependency Injection

There are some cases in which unit test don't work for the project.
I'm studing the Inversion of Control and Dependency Injection utilities and I would like to know if there are good reasons for use it than for make unit tests easier.
--update
Ok, let's analysis 1 of the cited advanteges: less coupling.
You take out the coupling from the child type, and you add coupling to the handler type who need to create the objects to inject.
Without unit testing, what's the advantage in this coupling transfer (not coupling eliminate).
IOC/DI bring some very important features to your application
Plugability: with DI you can inject dependency into the code without explicitly knowing how the functionality is actually working.
For example: your class might get a ILog interface injected so that it can write logs. Since the class works with the ILog interface, it would be possible to implement a FileLog, MemoryLog or a DatabaseLog & inject this into your class. Any of these implementation will work fine as long as they implement the ILog interface
Testability: With DI in your class, you can inject mock objects to test the behaviour of your class without actually needing the concrete implementation.
For example: consider a Controller class which needs a Repository to perform data operations. In this case, the repository can be DI for the controller. If you need to write tests on the Controller class, you can pass a DI'd mock version of the repository without having to work with the actual repository class
Configurability: Some of the common DI frameworks like Castle Windor, Unity, Spring etc., allow doing DI along with lifetime management of the object created. This is a very powerful feature & allow you to manage the dependencies & their lifetime via configuration. For example consider your application needs a ICache dependency. Via the configuration for lifetime & object management, you will be able to configure the cache to be a Per-application or per-session or per-request etc. without having to explicitly bake the implementation in your code.
HTH
IoC reduces coupling, which has a correlation with defect rates in some studies. (If that really long link doesn't work, it's to Software Engineering Quality Practices by Ronald Kirk Kandt.)
Sure, here are a few reasons:
Dynamic generation of proxies for remoting and transactons
Aspect oriented programming
Layering using interfaces and separation of implementation
Enough?
From the IoC wikipedia article:
There is a decoupling of the execution of a certain task from implementation.
Every system can focus on what it is designed for.
Every system does not make assumptions about what other systems do or should do.
Replacing systems will have no side effect on other systems.
While I would call the above feature list a bit vague, you see most of the above benefits, even without testing.
If I had to say it in a nutshell, I would say that IoC significantly improves separation of concerns which is a valuable goal in software development.
Yes, dependency injection helps you make your classes more focused, clearer*, and easier to change, because it makes it easier to adhere to the single-responsibility principle.
It also makes it easier to vary parts of your application independently of one another.
When you use constructor injection in particular, it's easier to tell what your code needs to do its job. If the WeatherUpdater class requires an IWeatherRepository in its constructor no one is surprised that it uses a database.
* Again, constructor injection only.

When do you use dependency injection?

I've been using StructureMap recently and have enjoyed the experience thoroughly. However, I can see how one can easily get carried away with interfacing everything out and end up with classes that take in a boatload of interfaces into their constructors. Even though that really isn't a huge problem when you're using a dependency injection framework, it still feels that there are certain properties that really don't need to be interfaced out just for the sake of interfacing them.
Where do you draw the line on what to interface out vs just adding a property to the class?
The main problem with dependency injection is that, while it gives the appearance of a loosely coupled architecture, it really doesn't.
What you're really doing is moving that coupling from the compile time to the runtime, but still if class A needs some interface B to work, an instance of a class which implements interface B needs still to be provided.
Dependency injection should only be used for the parts of the application that need to be changed dynamically without recompiling the base code.
Uses that I've seen useful for an Inversion of Control pattern:
A plugin architecture. So by making the right entry points you can define the contract for the service that must be provided.
Workflow-like architecture. Where you can connect several components dynamically connecting the output of a component to the input of another one.
Per-client application. Let's say you have various clients which pays for a set of "features" of your project. By using dependency injection you can easily provide just the core components and some "added" components which provide just the features the client have paid.
Translation. Although this is not usually done for translation purposes, you can "inject" different language files as needed by the application. That includes RTL or LTR user interfaces as needed.
Think about your design. DI allows you to change how your code functions via configuration changes. It also allows you to break dependencies between classes so that you can isolate and test objects easier. You have to determine where this makes sense and where it doesn't. There's no pat answer.
A good rule of thumb is that if its too hard to test, you've got some issues with single responsibility and static dependencies. Isolate code that performs a single function into a class and break that static dependency by extracting an interface and using a DI framework to inject the correct instance at runtime. By doing this, you make it trivial to test the two parts separately.
Dependency injection should only be used for the parts of the
application that need to be changed dynamically without recompiling
the base code
DI should be used to isolate your code from external resources (databases, webservices, xml files, plugin architecture). The amount of time it would take to test your logic in code would almost be prohibitive at a lot of companies if you are testing components that DEPEND on a database.
In most applications the database isn't going to change dynamically (although it could) but generally speaking it's almost always good practice to NOT bind your application to a particular external resource. The amount involve in changing resources should be low (data access classes should rarely have a cyclomatic complexity above one in it's methods).
What do you mean by "just adding a property to a class?"
My rule of thumb is to make the class unit testable. If your class relies on the implementation details of another class, that needs to be refactored/abstracted to the point that the classes can be tested in isolation.
EDIT: You mention a boatload of interfaces in the constructor. I would advise using setters/getters instead. I find that it makes things much easier to maintain in the long run.
I do it only when it helps with separation of concerns.
Like maybe cross-project I would provide an interface for implementers in one of my library project and the implementing project would inject whatever specific implementation they want in.
But that's about it... all the other cases it'd just make the system unnecessarily complex
Even with all the facts and processes in the world.. every decision boils down to a judgment call - Forgot where I read that
I think it's more of a experience / flight time call.
Basically if you see the dependency as a candidate object that may be replaced in the near future, use dependency injection. If I see 'classA and its dependencies' as one block for substitution, then I probably won't use DI for A's deps.
The biggest benefit is that it will help you understand or even uncover the architecture of your application. You'll be able to see very clearly how your dependency chains work and be able to make changes to individual parts without requiring you to change things that are unrelated. You'll end up with a loosely coupled application. This will push you into a better design and you'll be surprised when you can keep making improvements because your design will help you keep separating and organizing code going forward. It can also facilitate unit testing because you now have a natural way to substitute implementations of particular interfaces.
There are some applications that are just throwaway but if there's a doubt I would go ahead and create the interfaces. After some practice it's not much of a burden.
Another item I wrestle with is where should I use dependency injection? Where do you take your dependency on StructureMap? Only in the startup application? Does that mean all the implementations have to be handed all the way down from the top-most layer to the bottom-most layer?
I use Castle Windsor/Microkernel, I have no experience with anything else but I like it a lot.
As for how do you decide what to inject? So far the following rule of thumb has served me well: If the class is so simple that it doesn't need unit tests, you can feel free to instantiate it in class, otherwise you probably want to have a dependency through the constructor.
As for whether you should create an interface vs just making your methods and properties virtual I think you should go the interface route either if you either a) can see the class have some level of reusability in a different application (i.e. a logger) or b) if either because of the amount of constructor parameters or because there is a significant amount of logic in the constructor, the class is otherwise difficult to mock.

Resources