Replace Spring.Net IoC with another Container (e.g. Ninject) - dependency-injection

I'm curious to know if it's possible to replace Spring.Net's built-in IoC container with Ninject. We use Ninject on my team for IoC in our other projects so I would like to continue using that container if possible.
Is this possible? Has anyone written a Ninject-Spring.Net Adapter??
Edit
I like many parts of the Spring.Net package (the data access, transactions, etc.) but I don't really like the dependency injection container. I would like to replace that with Ninject
Thanks

I can't talk specifically about converting Spring.NET to Ninject, but in general, all application code should be written to be DI Container-agnostic.
The best way to think about DI Containers is the Hollywood Principle. In DI terms, it becomes, don't call the DI Container, it'll call you.
In other words, the best application of DI is to use simple patterns such as Constructor Injection and Abstract Factory.
Most DI Containers worth their salt inherently understand these patterns, so no special, DI Container-specific, jumping through hoops should be needed.
This also means that ideally, you should only have DI Container-specific code in a single file in your application. This place is called the Composition Root, and this is where the DI Container wires up the entire object graph and gets out of the way.
If you follow this principle, you can easily exchange one DI Container for another.
The following posts have more details:
Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)
Design - Where should objects be registered when using Windsor

Jeffrey, can you please provide an example of what you are trying to do? I do not see your point, why/where/how you want to mix the 2 containers. If your code is entirely container-agnostic, then you won't have any problems to use either container for doing the wiring.

I meant everything I said in my other answer. However, I also realize that if you currently use Spring.NET as a Service Locator (i.e. you have code sprinkled all over your code base that queries the container), that answer may not be very helpful.
If this is the case, you may find the Common Service Locator project helpful. It is an open source project that attempts to abstract away specific Service Locators, hiding them all behind a common interface.
While they don't seem to have a Ninject implementation, they do have a Spring.NET implementation, so maybe that can take you halfway there.
For the record, I consider Service Locator an anti-pattern, and find that the Common Service Locator is the wrong answer to the wrong problem. In my eyes, it is utterly redundant, but it may be helpful to you as an intermediate step.

Related

Best Practice for Using a Dependency Injection / Service Locator Container?

TLDR: What is the best way to use an IoC container once you have it configured?
I've been reading up on IoC (Dependency Injection, Service Locators, etc.). I get DI is good and that IoC containers can make it easier to instantiate objects, but what I have not found is anything that shows how to actually use the injection container once you have it configured. Most tutorials stop at just getting the container setup and send you on your way, but for some reason it's just not clicking as to how to best utilize your injection container once it's configured.
From what I can tell there are 2 ways I could use a container:
Instantiate every conceivable dependency up front and have those flow through the application via a single entry point with a potentially massive number of dependencies.
This seems silly because you may be creating lots of class instances you don't really need. It also seems that you would hardly need a container to do this.
Move the injection container to some global scope and call it whenever I need a new object that has dependencies.
This seems silly because a.) now you created a global/singleton (barf) and b.) now your dependency injector iteself is a dependency.
Both of these options don't seem ideal, so I'm wondering if I'm just missing something fundamental about how an injection container is intended to be used in practice. Any help would be appreciated!
You are looking for the concept of object lifetimes. Autofac has a great primer on the subject.

verifiying I understand the difference between IoC, Ioc Container, DI and service locator

read many posts about the difference between the 3 idioms. But got more confused, then I ran into this article:
http://martinfowler.com/articles/injection.html
just want to see if I got this right. please correct me if I'm wrong.
Please notify me of correction and additions:
IoC- is the concept of decoupling an application from the implementation of a service it uses. The application contain a ref to Iservice and is not incharge of instanciating the concrete service.
There are at least two way to achive so:
DI - The concrete service is injected as a ctor param/throw a setter/throw interface injection (what does the latter mean?)
ServiceLocator - is a component that knows all the concrete services the application may need. The application explicitly asks for the concrete service from the Locator.
*IoC container is actualy a controls' factory ("provider").
I got a bit confused by the "when to prefer (1) or (2)" part in the article. could someone please tell from his own experience in a layman words ?
"Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice."--> How is locator more straightforward ? because it uses method invocation explicitly ? What is it better to use DI when there are multiple applications?
IoC is the concept of decoupling an application from the implementation of a service it uses.
It is true that IoC goes hand in hand with decoupling interfaces from implementations, but I see it as a more general principle. This SO answer gives a very good explanation of the concept.
There are at least two way to achive so:
1) DI
2) ServiceLocator
I wouldn't say that the Service Locator pattern is an example of Inversion of Control. Quite the opposite - when you are using the Service Locator, you are acquiring the required dependencies in active way, nobody else does it for you (contrary to the DI, where the container handles the dependencies for you, you just have to give it a possibility of doing so - a setter, a constructor parameter or by implementing method of injection interface).
How is locator more straightforward ? because it uses method invocation explicitly?
I think that Martin Fowler is referring to the general idea of IoC that may make the code harder to understand if you've never seen the IoC/DI concept used before. On the other hand, the code using Service Locator to acquire some dependencies may be easier to grasp on first encounter.
What is it better to use DI when there are multiple applications?
When you are creating a component that is supposed to be reusable, the advantage of DI is that it doesn't make your component dependent on anything else than the original dependency (in MF's example, the MovieLister depends only on the MovieFinder interface when using DI).
Also, it is quite easy for others to use your component - the just have to pass the dependencies using the means of DI you provided.
When using the Service Locator, you also add dependency on the interface of the Service Locator itself. With segregated interface for the Locator, that may not be a problem. But it may also be harder for users of your component to satisfy the dependencies of your component, as MF writes:
The difference comes if the lister is a component that I'm providing to an application that other people are writing. In this case I don't know much about the APIs of the service locators that my customers are going to use. Each customer might have their own incompatible service locators.

Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)

I have a solution with two relevant (to this question) projects, and a few others;
Class library with functionality used by several other projects.
ASP.NET MVC application.
My question is basically where I should do IoC with Ninject 2, considering...
The class library needs some DI love, among other things in the repository classes which need web request specific session objects (think Unit of Work).
The MVC app needs DI since with Ninject 2 you basically inherit from NinjectHttpApplication.
Unit tests for the class library need to be aware of this to inject a different set of repositories.
Unit tests for the web app need to be injected for the same reason.
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
I can't do DI only in the class library since the MVC app needs to inherit from NinjectHttpApplication to begin with.
I can't do DI only in the MVC app - the class library is used by other libraries, after all, and the MVC app shouldn't know too much about the internals of the library anyway.
I guess this is the only way out I can see: Independent IoC for both projects. The class library and the MVC app each have their own IoC setup and do DI for their stuff without really caring about each other.
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
Thanks!
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.

What other IoC containers have an IInitializable like feature?

I've been using Castle Windsor in my previous project and I liked it a lot. For my current project I'm looking to use a different IoC container. Castle Windsor hasn't had any new releases since 2007 and is still not at version 1.0 so it is hard to justify using it in a commercial environment.
One of the things I like about Castle Windsor is that you can have the container call an Initialize method on your services after all dependencies have been set simply by making the service implement IInitializable. I used this a lot. It makes it easy to do property injection instead of constructor injection and that cleans up code and tests quite a bit.
I've been looking at StructureMap, AutoFac, Unity and Spring.Net as alternatives but of these only Spring.Net supports something similar, it automatically calls an Init() method. Unfortunately Spring.Net does not really support the way I want to work with an IoC container (it injects based on string keys instead of interface declarations and therefore its autowiring support is limited too)
Did I miss a similar feature in the IoC containers I looked at? Is my way of working with IoC containers wrong somehow? Or are there other IoC containers that do support something like IInitializable or Init()?
Autofac can do it - they call it Startable
With StructureMap, you could do something like this:
ForRequestedType<IFoo>()
.TheDefaultIsConcreteType<Foo>()
.OnCreation(x => x.Init());
It's not as easy as implementing an 'Initialisation' interface on your class, but it also means you don't need to tie your class implementation to your choice of DI container by inheriting from a DI container specific interface (although I'm not sure how much of an issue that is in reality).
I believe that constructor injection is far more commonly used right now, and property injection is widely seen as a fallback for cases where it is not feasible to get the DI Container to perform object construction for you (e.g. ASP.NET webforms). I could be wrong there though, that's just my view on the subject!
Do you really think that property injection "cleans up code and tests quite a bit"? That's interesting because I sort of think the opposite - I think constructor injection is 'cleaner', and I'm guessing that could be simply because that's how I normally do it so that's what I'm used to. :)
Castle may not have had any release in some time, but it's still actively developed. You can get latest (pretty stable) builds here.
There also is going to be an official v2.0 release quite soon. Why not use what you already know, if you know that it's good?
LinFu.IOC has it--it's called IInitialize. You can find it here: github.com/philiplaureano/LinFu

IoC Containers and Domain Driven Design

I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
IOC containers are invaluable when designing unit-testable code and are orthogonal to DDD. You could create your own implementation of factory and builder patterns if you want...by why go through the trouble?
Absolutely. Use an IOC container that's just powerful enough to meet you specific requirements; no more, no less.
We use DDD, and dependency injection (the pattern), but do not use a dependency injection framework.
One problem with popular dependency injection frameworks is how they separate configuration into XML files. XML is a great markup language. How it became a configuration language, I will never understand. The issue, of course, is that you have to run the application before you know if everything is wired up correctly. It is also hard to see what code is used where. If you are using interfaces, then the only reference to an implementation will be in an XML file, which is harder to spot. And finally you lose type safety and generics. (I once saw a horrible bug in production which would have been caught by the compiler had we not been using XML.)
I should point out that I am not saying that dependency injection is bad. It is a fundamental pattern of good object design. But there is absolutely nothing wrong with doing wiring in a factory.
At my last two projects we have removed large amounts of "code" out of XML files, and into factories. The factories are wired up with container managed services (such as JDBC connections, JMS connections and so forth). The application has become much simpler to understand, because the factory is less verbose than XML. And as a Java programmer, it is much easier to wire together a program using control-space, instead of XML twiddling - and your IDE will highlight when you have broken something.
In an integration test, just create the objects as you would in a factory.
ie,
dbConnection = DatabaseConnectionFactory.connection();
serviceUnderTest = new PaymentProcessor(new CustomerRepository(connection));

Resources