Should I encapsulate my IoC container? - ioc-container

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I'm trying to decide whether or not it makes sense to go through the extra effort to encapsulate my IoC container. Experience tells me that I should put a layer of encapsulation between my apps and any third-party component. I just don't know if this is bordering on overkill.
I can think of situations where I might want to switch containers. For instance, my current container ceases to be maintained, or a different container is proven to be more light-weight/performant and better fits my needs. If this happens, then I'll potentially have a lot of re-wiring to do.
To be clear, I'm considering encapsulation of the registration and resolution of types. I think it's a no-brainer to encapsulate resolution - I'd hope it's common practice to have a helper/util class delegating to the container.
EDIT:
The assumption is that I prefer to wire-up my types programmatically for type-safety, compile-time checking and refactorability. It's this code and its dependency on the container that I'm looking to protect myself from.
I've also been using an IoC container for several other projects that share a lot of the same relationships, but the container is a pain to work with so I want change. But, a change means I lose the reusability of the registration code. Hence, why I'm contemplating encapsulation. It's not a huge burden, but one that I'd, nevertheless, like to mitigate.
I'm looking to:
Minimize the impact of change in containers / versions of containers
Provide some level of type-registration consistency across projects that may use different containers
Provide interface methods that make sense to me (RegisterSingleton<T,T> rather than RegisterType<T,T>( SomeLifetimeProvider ) - using Unity as an example).
Augment the container as conditions/scalability requirements change e.g. adding better caching, logging, etc during resolution/registration.
Provide my own model for registering type mappings.
Say I want to create a bunch of RegistrationHandler objects in an assembly/package and so I can easily segregate registration responsibilities across multiple classes and automatically pickup these handlers without changing code anywhere else.
I realize this is a bit subjective, so pros/cons might be helpful
Thanks!

Do it later, and only if you actually have the need to change IOC containers.
Pick an IOC container that is non-invasive. That is, one where the objects being connected to each other don't have any dependencies on the IOC container. In this case, there's nothing to encapsulate.
If you have to pick an IOC container that requires that you have dependencies on the container, choose one with the simplest dependencies/API you can. If you need to replace this IOC container (and you probably won't), implement adapters that bridge the new API to the old one.
In other words, let the first IOC container be the one that defines the interfaces for any future container so that you don't have to invent your own, and you can delay any of this sort of work until you absolutely need it.
EDIT:
I don't see a way of guaranteeing type-safety short of either:
Designing a relatively complex implementation of the Builder pattern along with visitor implementations that would write IOC configuration files, or something equivalent.
Implementing a type-safe IOC configuration DSL. (My choice if I had multiple apps that required swappable IOC containers.)

Yeah go for it. It's not a whole lot of extra effort and like you say, it gives you better isolation from third party components.
It also means that you can easily switch out the IoC container if you find something that's better. I recently did this with swapping out the Spring.net IoC container for structuremap.
The ASP.NET MVC Contrib project on codeplex is a pretty good place to start. This is what I based my implementation off.

It's best practice to do something only if there's an actual need for it, and never code something that you guess to be required sometimes in the future (that's the so-called YAGNI-principle). If your architecture is ok, you can easily change the container, if it actually should become necessary...
If you think you need this kind of flexibility, you may look at the Common Service Locator project at CodePlex. It does exactly what you look for: providing a common facade for various IoC containers.
HTH!

Rather than encapsulating the IOC container itself, I prefer to isolate the locus of interaction with the IOC container. For example, in ASP.Net MVC, I generally limit the exposure to the container to the controller factory and the global.aspx.cs file, where it's usually setup.
In my mind, having a lot of code that knows about the IOC container is an antipattern that increases complexity. I've seen a fair amount of code in which objects feel free to ask the IOC container for their dependencies, and then they've basically reduced the IOC container to a high-maintenance Service Locator.
Since IOC containers can resolve dependencies to an arbitrary degree of depth, it's pretty easy to make the controller factory the component that's responsible for involving the inversion of control containers. The constructor for each controller essentially specifies the services/repositories/gateways it needs.
For any of my apps, swapping the IOC container would essentially be a matter of rewriting the code the configures the container (specifies the bindings, etc.) and hooks up the controller factory. For apps exposed as services, the same basic idea should be reasonably manageable, though depending on the constraints of your runtime, you might have to use setter injection rather than constructor injection.

Related

How to "override a binding" in a ZLayer?

When working with ZIO layers you have to deal with a whole different concept of what dependency injection is.
Usual approach is not completely typesafe and depends on some form of runtime reflection, and a container that registers constructors and built instances (in case they're supposed to be singletons).
I, for instance, when working with Kotlin, tend to use Kodein (pretty awesome library), and Kodein uses the usual approach of building a container, binding constructors and well, the usual DI stuff
When working with ZIO layers there are no containers, there are no bindings, it's just plain old function composition on steroids.
I prefer that approach, but I'm missing a feature that only the traditional approach has: overriding bindings.
With that feature I can take my actual application container and surgically replace one of its bindings in order to do test different parts of the system, connected to the rest of the app.
More given the fact that with the usual approach there's no such thing as hidden dependencies (nor explicitly visible).
Anyway... Is there a way to achieve kind of a similar feature? If so, how?

Implementing .Net DI Compile Time Proxies?

I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.

What criteria should one used to determine if Dependency Injection Framework should be used? [duplicate]

I've had a certain feeling these last couple of days that dependency-injection should really be called "I can't make up my mind"-pattern. I know this might sound silly, but really it's about the reasoning behind why I should use Dependency Injection (DI). Often it is said that I should use DI, to achieve a higher level of loose-coupling, and I get that part. But really... how often do I change my database, once my choice has fallen on MS SQL or MySQL .. Very rarely right?
Does anyone have some very compelling reasons why DI is the way to go?
Two words, unit testing.
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up 'test' data.
DI is very useful for decoupling your system. If all you're using it for is to decouple the database implementation from the rest of your application, then either your application is pretty simple or you need to do a lot more analysis on the problem domain and discover what components within your problem domain are the most likely to change and the components within your system that have a large amount of coupling.
DI is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain.
How relevant it is to your project depends upon the expected lifespan of your code. Depending on the type of work you're doing zero reuse from one project to the next for the majority of code you're writing might actually be quite acceptable.
An example for use the use of DI is in creating an application that can be deployed for several clients using DI to inject customisations for the client, which could also be described as the GOF Strategy pattern. Many of the GOF patterns can be facilitated with the use of a DI framework.
DI is more relevant to Enterprise application development in which you have a large amount of code, complicated business requirements and an expectation (or hope) that the system will be maintained for many years or decades.
Even if you don't change the structure of your program during development phases you will find out you need to access several subsystems from different parts of your program. With DI each of your classes just needs to ask for services and you're free of having to provide all the wiring manually.
This really helps me on concentrating on the interaction of things in the software design and not on "who needs to carry what around because someone else needs it later".
Additionally it also just saves a LOT of work writing boilerplate code. Do I need a singleton? I just configure a class to be one. Can I test with such a "singleton"? Yes, I still can (since I just CONFIGURED it to exist only once, but the test can instantiate an alternative implementation).
But, by the way before I was using DI I didn't really understand its worth, but trying it was a real eye-opener to me: My designs are a lot more object-oriented as they have been before.
By the way, with the current application I DON'T unit-test (bad, bad me) but I STILL couldn't live with DI anymore. It is so much easier moving things around and keeping classes small and simple.
While I semi-agree with you with the DB example, one of the large things that I found helpful to use DI is to help me test the layer I build on top of the database.
Here's an example...
You have your database.
You have your code that accesses the database and returns objects
You have business domain objects that take the previous item's objects and do some logic with them.
If you merge the data access with your business domain logic, your domain objects can become difficult to test. DI allows you to inject your own data access objects into your domain so that you don't depend on the database for testing or possibly demonstrations (ran a demo where some data was pulled in from xml instead of a database).
Abstracting 3rd party components and frameworks like this would also help you.
Aside from the testing example, there's a few places where DI can be used through a Design by Contract approach. You may find it appropriate to create a processing engine of sorts that calls methods of the objects you're injecting into it. While it may not truly "process it" it runs the methods that have different implementation in each object you provide.
I saw an example of this where the every business domain object had a "Save" function that the was called after it was injected into the processor. The processor modified the component with configuration information and Save handled the object's primary state. In essence, DI supplemented the polymorphic method implementation of the objects that conformed to the Interface.
Dependency Injection gives you the ability to test specific units of code in isolation.
Say I have a class Foo for example that takes an instance of a class Bar in its constructor. One of the methods on Foo might check that a Property value of Bar is one which allows some other processing of Bar to take place.
public class Foo
{
private Bar _bar;
public Foo(Bar bar)
{
_bar = bar;
}
public bool IsPropertyOfBarValid()
{
return _bar.SomeProperty == PropertyEnum.ValidProperty;
}
}
Now let's say that Bar is instantiated and it's Properties are set to data from some datasource in it's constructor. How might I go about testing the IsPropertyOfBarValid() method of Foo (ignoring the fact that this is an incredibly simple example)? Well, Foo is dependent on the instance of Bar passed in to the constructor, which in turn is dependent on the data from the datasource that it's properties are set to. What we would like to do is have some way of isolating Foo from the resources it depends upon so that we can test it in isolation
This is where Dependency Injection comes in. What we want is to have some way of faking an instance of Bar passed to Foo such that we can control the properties set on this fake Bar and achieve what we set out to do, test that the implementation of IsPropertyOfBarValid() does what we expect it to do, i.e. return true when Bar.SomeProperty == PropertyEnum.ValidProperty and false for any other value.
There are two types of fake object, Mocks and Stubs. Stubs provide input for the application under test so that the test can be performed on something else. Mocks on the other hand provide input to the test to decide on pass\fail.
Martin Fowler has a great article on the difference between Mocks and Stubs
I think that DI is worth using when you have many services/components whose implementations must be selected at runtime based on external configuration. (Note that such configuration can take the form of an XML file or a combination of code annotations and separate classes; choose what is more convenient.)
Otherwise, I would simply use a ServiceLocator, which is much "lighter" and easier to understand than a whole DI framework.
For unit testing, I prefer to use a mocking API that can mock objects on demand, instead of requiring them to be "injected" into the tested unit from a test. For Java, one such library is my own, JMockit.
Aside from loose coupling, testing of any type is achieved with much greater ease thanks to DI. You can put replace an existing dependency of a class under test with a mock, a dummy or even another version. If a class is created with its dependencies directly instantiated it can often be difficult or even impossible to "stub" them out if required.
I just understood tonight.
For me, dependancy injection is a method for instantiate objects which require a lot of parameters to work in a specific context.
When should you use dependancy injection?
You can use dependancy injection if you instanciate in a static way an object. For example, if you use a class which can convert objects into XML file or JSON file and if you need only the XML file. You will have to instanciate the object and configure a lot of thing if you don't use dependancy injection.
When should you not use depandancy injection?
If an object is instanciated with request parameters (after a submission form), you should not use depandancy injection because the object is not instanciated in a static way.

Antipatterns of IoC container usage. Why IoC containers are so complex and used so "fancy" way?

I'm seriously start thinking that usage of IoC container provokes to create overdesigned solutions (at least it provokes me to try to use various unnecessary features:).
It's the time to synchronize my "IoC" antipatterns list with community one's..
My short experience tell that it is absolutely enough to call Resolve method once per application at startup to resolve some infrastructure singletons and initiate with them "transient object's factory" that could produce new "smaller life time grain factories" . Even to make those factories thread safe (e.g. create one instance per thread) is so easy to achieve by adding 10 code lines into factory... Still those factories are much more simpler then "library's integration with IoC tool". Interception? Just create your own wrappers... Life time managers / dependency strategies/ parent containers? Call the Resolve only once at bootstrapper and you won't think about that.
Could you help me to understand why developers call Resolve several times on different application layers (by passing container or by passing delegate to container) and then have a lot of things to think about? I really worry that I miss something.
Some kind of IoC are anti-patterns or may be in some cases. For example the service locator antipattern. But if you are using constructor injection at the beginning of your application - and only there - then it should not lead to an anti-pattern.
Injecting a DI container interface in a class is a wrong use of constructor injection. If DI is not part of the business logic of your class it should not know or depend on DI container nor should it depend on IKitchen. It's only fine to inject your DI container in some kind of helper or service working in conjunction with your dependency injection container, because it's purpose is to work with or around DI container. The examples in the links you give are misuse of IoC. It does not mean that IoC in general is an anti-pattern.
I think the correct question would be "Can constructor injection be an anti-pattern?". So far I've never faced any situation or seen any example where it was so I would say "no", until I face such a situation.
When it was not clear to me how to use an IoC container, I decided to stop using it, because I thought was just an overcomplication over the simple dependency injection.
It is true though that even without IoC is possible to fall in the over-injection cases.
A while ago I read some posts from the author of ninject that opened my mind.
As you already know the injector should be used only inside the context root. However, in order to avoid over-injections, I decided to introduce an exception of the rule for injected factories.
In my framework, factories (and only factories) can use the injector container. Factories are binded in the container in the context root and therefore can be injected. Factories become valid dependencies and are used to create new objects inside other objects, using the injector container to facilitate dependencies injection.
Read This
Clearly something wrong. New library should not bring additional complex code.
I've found somebody who possibly could understand me :)
Constructor over-injection anti-pattern
Other antipattern in my eyes is pushing the initialization of container "deeper" then actual bootsrapper.
For example Unity and WCF recommendations
Bootstrapper in wcf app is the service constructor, then just put container initialization to constructor. I do not understand reasons to recommend to go for programming wcf sevice behaiviors and custome sevice host factory: if you want to have "IoC container free" bootstrapper - it is absurd, if you need to have "IoC container free" service contract implementation - just create second "IoC container free" service contract implementation.

The IOC "child" container / Service Locator

DISCLAIMER: I know there is debate between DI and service locator patterns. I have a question that is intended to avoid the debate. This question is for the service locator fans, who happen to think like Fowler "DI...is hard to understand...on the whole I prefer to avoid it unless I need it." For the purposes of my question, I must avoid DI (reasons intentionally not given), so I'm not trying to spark a debate unrelated to my question.
QUESTION: The only issue I might see with keeping my IOC container in a singleton (remember my disclaimer above), is with the use of child containers. Presumably the child containers would not themselves be singletons. At first I thought that poses a real problem. But as I thought about it, I began to think that is precisely the behavior I want (the child containers are not singletons, and can be Disposed() at will).
Then my thoughts went further into a philosophical realm. Because I'm a service locator fan, I'm wondering just how necessary the notion of a child container is in the first place. In a small set of cases where I've seen the usefulness, it has either been to satisfy DI (which I'm mostly avoiding anyway), or the issue was solvable without recourse to the IOC container. My thoughts were partly inspired by the IServiceLocator interface which doesn't even bother to list a "GetChildContainer" method.
So my question is just that: if you are a service locator fan, have you found that child containers are usually moot? Otherwise, when have they been essential?
extra credit: If there are other philosophical issues with service locator in a singleton (aside from those posed by DI advocates), what are they?
IMHO:
Child containers have nothing to with service locators, i.e. they're orthogonal. Using a container as a service locator is just that, a way to use it, and it has nothing to do with the container supporting child containers or not.
Child containers usage depend largely on container design. For example, while Windsor supports them, they're seldomly used. Autofac OTOH uses them heavily to manage scope / component lifecycles. And it's an entirely optional feature of any container / service locator implementation, that's why IServiceLocator doesn't mention it. IServiceLocator's job is to provide the lowest common denominator in a service locator.