StyletIoC Introduction - canton7/Stylet GitHub Wiki
StyletIoC is a very lightweight and extremely fast IoC container. It was designed to do only a few things, but to do them very well and in an intuitive manner.
It's configured using a fluent interface - none of this XML rubbish. It also has zero dependencies.
I'm going to assume for now that you're reasonably confident with the concept of an IoC container - if not, do some reading and come back. I may write a more in-depth introduction in the future.
StyletIoC is constructed around the concept of a service. A service is a concrete type, abstract type, or interface, which is (or can be) implemented by a concrete type, for example:
interface IVehicle { ... }
class HotHatchback : IVehicle { ... }
Here, IVehicle
is the service, and HotHatchback
is the concrete type which implements it. Note that HotHatchback
is also a service - one that is implemented by the HotHatchback
class itself.
When you configure StyletIoC, you define a set of relationships. Each relationship is between a service, and the type (or types) which implement it. So here, we could tell StyletIoC "create a relationship between the service IVehicle
, and the type HotHatchback
".
Later, when you want an implementation of IVehicle
, you can ask StyletIoC "give me an instance of something which implements the service IVehicle
, and StyletIoC wil construct a HotHatchback
and pass it back to you.
There are 3 ways to get StyletIoC to construct a type for us:
- By calling
IContainer.Get
directly - Constructor Injection
- Property Injection
Calling IContainer.Get
directly is the easiest to explain, and looks something like this:
var ioc = ... // Covered in lots of detail elsewhere
var vehicle = ioc.Get<IVehicle>();
As tempted as this may look, this should only be done in the root of your application - use Constructor Injection and Parameter Injection elsewhere.
When StyletIoC constructs a type for you, it will look for a constructor which has parameters of types which it knows how to resolve. It will then resolve those types, and inject them into the constructor. For example:
class Engine { ... }
class Car
{
public Car(Engine engine)
{
// 'engine' contains a new instance of Engine
}
}
This is the most common way of new instances of things out of StyletIoC - every type which StyletIoC constructs lists its dependencies in its constructor, and StyletIoC will construct each of those, injecting its dependencies as it does.
If you wish, you can also do parameter injection, provided that the parameter to be injected has the attribute [Inject]
, for example:
class Engine { ... }
class Car
{
[Inject]
public Engine Engine { get; set; }
}
The various merits of each are discussed elsewhere.