1. Why IOC is needed
When there is no IOC, the code is written like this:
Imyservice service = new MyService ();
The MyService implements the interface IService.
The disadvantage is that there is no separation between the interface and the implementation (directly referencing the MyService)
With the IOC, it's something like this:
IService service = container. Resolve<iservice> ();
Where container is the IOC container, it is responsible (through the configuration file or assembly reflection) to find and instantiate the interface of the corresponding implementation class, to achieve the interface and implementation of the separation (no longer refer to the implementation class)
2, Castle Windsor
Castle Windsor is one of the IOC, official website: http://www.castleproject.org/. Other famous IOC also has Spring.net (Spring's. Net version) and so on.
A big difference between Castle Windsor and Spring is that the former is more likely to be configured as little as possible, while the latter is typically based on a configuration file (although you can also do without the configuration file)
3. Get the instance object of interface implementation class
The following code is an instance object that gets the implementation class for the interface IService:
Imyservice service = container. Resolve<imyservice> ();
The code is fairly concise.
If the constructor of the implementation class has parameters, you can call the corresponding overloaded method, passing in the argument (not recommended in this way):
Imyservice service = resolve<imyservice> (IDictionary arguments);
If the IService interface has more than one implementation, you can also call the ResolveAll method to return the array:
imyservice[] Services = container. Resolveall<imyservice> ();
4. Initialization of Castle Windsor
That is to get the container above to perform the resolve () method. Getting container is easy:
IWindsorContainer container = new WindsorContainer ();
The key is to register the component in container, which is to pair each interface with the implementation class, so that Windsor knows which class should execute the new XXX () when executing .resolve<iservice> ();
Container. Register (
component.for<imyservice> ()//interface
. Implementedby<myservice> ()//implementation class
);
This registers the interface Imyservice and the corresponding implementation class Myserviceimpl for Windsor, when calling container. When Resolve<imyservice> (), Windsor knows that the return new MyService () should be executed internally;
5, Questions:
Since our goal is the interface and implementation of the separation, before the introduction of Castle Windsor, the result of registration, and reference to the implementation class, this is not back to the original point. The answer is in the negative. Step 4 is just a demonstration of how to register by interface, in fact, there are many ways to register Windsor, described below.