Thursday, November 19, 2009

Injection in Unity

Ниже показаны типы Injection в Unity.
Unity выполняет регистрацию соответствия типов и экземпляров объектов.
Кроме этого, он может самостоятельно выполнять создание этих объектов по запросу.
Unity основан на ObjectBuilder, более простом и, на данный момент, устаревшем контейнере.

Injection может быть трех типов:
  1. Construction injection
  2. Property injection
  3. Method call injection
см. рис. ниже.


  • Constructor injection. This type of injection occurs automatically. When you create an instance of an object using the Unity container, it will automatically detect the constructor with the largest number of parameters and execute this, generating instances of each object defined in the constructor parameters. It resolves each parameter type through the container, applying any registrations or mappings for that type. If you want to specify a particular constructor for Unity to use, you can add the InjectionConstructor attribute to that constructor in the target class.
  • Property (setter) injection. This type of injection is optional. You can add the Dependency attribute to any property declarations that you want Unity to resolve through the container. Unity will resolve that property type and set the value of the property to an instance of the resolved type.
  • Method call injection. This type of injection is also optional. You can add the InjectionMethod attribute to any method declarations where you want Unity to resolve the method parameters through the container. Unity will resolve each parameter type and set the value of that parameter to an instance of the resolved type, and then it will execute the method. Method call injection is useful if you need to execute some type of initialization method within the target object.


Конфигурацию типа Injection можно выполнить в файле конфигурации в разделе контейнера, либо читая конфигурацию на запуске, либо динамически ее создавая перед конфигурированием приложения во время выполнения и далее она читается при конфигурировании.
Если в конфигурации не указан тип, который нужно разрешить во время выполнения, тогда Unity просто выполняет инстанцирование этого объекта, просматривая его конструктор. Если конструктор имеет параметры, аналогично, делается попытка найти эти параметры в контейнере. Есть опасность возникновения циклических зависимостей, когда происходит injection двух типов, каждый из которых в качестве параметров конструктора указывает на второй объект.

0 коммент.:

Post a Comment

Powered by Blogger.