轻量级MVVM框架Stylet介绍:(14) StyletIoC(Introduction to lightweight MVVM framework: (14) styleioc)

简介

StyletIoC轻量级的极快速的IoC容器。

服务和构建

StyletIoC是围绕服务的概念构建的。服务是具体类型、抽象类型或接口,由具体类型实现,例如:

interface IVehicle { ... }
class HotHatchback : IVehicle { ... }

这里IVehicle是服务,HotHatchback是实现它的具体类型。请注意,HotHatchback也是一个服务 – 由类本身实现的服务。

配置 StyletIoC 时,需要定义一组关系。每个关系都介于服务与实现它的类型(或多个类型)之间。所以在这里,我们可以告诉StyletIoC”在服务IVehicle和类型HotHatchback之间建立一种关系”。

稍后,当你想要实现IVehicle时,你可以要求StyletIoC”给我一个实现IVehicle服务的实例,StyletIoC将构造一个HotHatchback并将其传回给你。

解析类型 – 服务定位器和注入

有3种方法可以让StyletIoC为我们构建一个类型:

  • 通过直接调用IContainer.Get
  • 构造函数注入
  • 属性注入

直接调用IContainer.Get,如下例:

var ioc = ... // Covered in lots of detail elsewhere
var vehicle = ioc.Get<IVehicle>();

看起来很简单,但是缺点是只能在应用程序的根目录才能这样做,在其他地方还是需要使用构造函数和参数注入。

构造函数注入的例子

class Engine { ... }
class Car
{
   public Car(Engine engine)
   {
      // 'engine' contains a new instance of Engine
   }
}

属性注入的例子:

class Engine { ... }
class Car
{
   [Inject]
   public Engine Engine { get; set; }
}
————————

brief introduction

Styletoioc lightweight and extremely fast IOC container.

Service and build

Styletoioc is built around the concept of service. A service is a concrete type, abstract type or interface, which is implemented by a concrete type, for example:

interface IVehicle { ... }
class HotHatchback : IVehicle { ... }

Here, ivehicle is a service, and hothatcheback is the specific type that implements it. Note that hothatcheback is also a service – a service implemented by the class itself.

When configuring styleioc, you need to define a set of relationships. Each relationship is between the service and the type (or types) that implements it. So here, we can tell styleioc to “establish a relationship between the service ivehicle and the type hothatcheback”.

Later, when you want to implement iveslice, you can ask styleioc to “give me an instance of implementing iveslice service, and styleioc will construct a hothatcheback and pass it back to you.

Resolve type – service locator and injection

There are three ways for styleioc to build a type for us:

  • 通过直接调用IContainer.Get
  • Constructor Inject
  • Attribute injection

Call icontainer directly Get, for example:

var ioc = ... // Covered in lots of detail elsewhere
var vehicle = ioc.Get<IVehicle>();

It looks simple, but the disadvantage is that this can only be done in the root directory of the application. Constructors and parameter injection are still required elsewhere.

Constructor injection example

class Engine { ... }
class Car
{
   public Car(Engine engine)
   {
      // 'engine' contains a new instance of Engine
   }
}

Examples of attribute injection:

class Engine { ... }
class Car
{
   [Inject]
   public Engine Engine { get; set; }
}