Showing posts with label Unity Application Block. Show all posts
Showing posts with label Unity Application Block. Show all posts

Thursday, November 10, 2011

Unity 2 - InjectionMember usage


IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers);
What "injectionMembers" parameters are for?


The overload with the InjectionMember array is used, when you do not provide a configuration file, that the Unity container tells how to create an instance of the given type or if you want to create an instance on another way than defined in the configuration file. The overloads are used, when you want to configure an unity container without an configuration file. An InjectionMember can be an constructor, property or method call. The following code, taken from the Unity help, shows how to use InjectionMembers through the fluent interface of the container.

IUnityContainer myContainer = new UnityContainer();
myContainer.Configure<InjectedMembers>()
  .ConfigureInjectionFor<MyObject>( 
    new InjectionConstructor(12, "Hello Unity!"), 
    new InjectionProperty("MyStringProperty", "SomeText"));

<type type="MyObject" mapTo="MyObject" name="MyObject">
  <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> 
 
 
      <param name="someInt" parameterType="int"> 
        <value value="12"/>
      param> 
      <param name="someText" parameterType="string">
        <value value="Hello Unity!"/>
      param> 
    constructor> 
    <property name="MyStringProperty" propertyType="string">
      <value value="SomeText"/>
    property>
  typeConfig> type>
Another use case would be using InjectionFactory. For example:
var container = new UnityContainer();
container.RegisterType(new InjectionFactory((c) => Customer.NewCustomer()));
var newCustomer = container.Resolve();
Console.WriteLine(newCustomer.Name);

I use InjectionFactory when there is no chance to add an injection attribute for a third party class constructor or property. In this case you can create delegate creating an object.

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 двух типов, каждый из которых в качестве параметров конструктора указывает на второй объект.

Friday, November 13, 2009

MVP и Unity

Источник: http://gandjustas.blogspot.com/2009/06/mvp-unity.html

MVP – Model View Presenter – паттерн организации PL (presentation layer – уровень представления).

MVP применяется при создании десктопных интерфейсов. Выделяют три комопнента: есть модель – группа классов, которые отдают данные или получают команды, представление – форма обладающая состоянием и некоторым поведением. Презентер создают для отделения бизнес-логики от деталей GUI-фреймворка. В отличие от MVC в MVP представление определяет презентер, а не наоборот.

MVP обычно строится вокруг существующих GUI-фреймворков. На практике существуют две принципиально различные различные реализации паттерна – Supervising Controller и Passive View.
В первом случае логика помещается в обработчики событий button_click, а сами обработчики помещаются в отдельный класс. Для полной изоляции презентера от деталей представления надо писать достаточно много врапперов\адаптеров.
Во втором случае создается пара интерфейсов для общения между представлением и презентером. При совершении какого-либо действия представление напрямую обращается к презентеру, тот выполняет некоторый код и вызывает установку свойств представления. Passive View способствует максимальному перемещению кода в в презентер, что облегчает тестирование.

Реализация: Presenter содержит ссылки на View и сервис. Он использует сервисы, обновляет данные, отправляет команды во View. View содержит ссылку на Presenter. При обработке клика на кнопке он отправляет команды в Presenter.

Wednesday, November 4, 2009

Prism, Composite Application Guidance, CompositeWPF: общие положения

Monday, November 2, 2009

Unity Application Block



//TODO: У этого же пользователя есть интересные доклады на тему криптографии. Посмотреть.

//MVP + Unity - хороший пример использования, да и сам блог содержит много полезной информации.

Powered by Blogger.