Posts tagged inversion of control

Supporting Inversion of Control

As you know, I am a big supporter of Inversion of Control. Fortunately the discussion whether to use IoC (and a container) or not is over. We won, period. But this post will be about other type of support.

Because of IoC becoming so ubiquitous, statements like these

Our framework has very good support for IoC

Adding support for IoC is the goal of the next release

We support Inversion of Control containers such as Autofac, Windsor, Unity…

are becoming more popular on project blogs and roadmaps. Recently, ASP.NET has been guilty of this sin. I admit I was guilty too. What’s the problem you ask? The answer is simple. Inversion of Control does not need any support from your frameworks. Adding it does not solve any problem while it introduces a ton of new ones.

So-called support for IoC manifests itself in baking some abstraction of either Service Locator or whole container into the particular framework. Then you have ’satellite’ assemblies that implement this abstraction based on particular container. One of the problems is, the satellites have to be updated every time the container they depend on gets updated. If the container uses strong naming, it makes things even worse. Also, someone has to build all these implementations. Usually the author of the project builds one or two (for his favourite containers) and leaves the task to implement other to the community (you).

Some people may say that they need an IoC container in their framework because it is so damn complex that they cannot live without it. First of all, I think this is a code smell that suggest something is wrong with the design of the framework. But if you insist on not redesigning but using IoC instead, please ilmerge and internalize the container. I don’t want to see it. The most weird realization of this concept of using IoC container in the internals of the framework I’ve ever seen caused that nice, fluent, configuration API instead of configuring the framework directly, was putting things into the container so that they could be retrieved later.

The problem that people who introduce IoC support into their framework are trying to solve is the creation of your (application developer’s) components inside the framework. The idea of framework is, you pass some code to it and it will call it whenever it needs it. In languages such as C# it often means passing some type objects to the framework which are to be used to create instances later on. If you embrace IoC in your application (and as I said in the preface, I strongly believe you should do so) you expect dependencies to be injected to your components. But how can framework inject dependencies? It has to use the same container as you are using in the rest of the application. But instead of building huge abstractions over containers and trying to implement them, how about defining something as simple as this

public interface IObjectFactory
{
    object GetInstance(Type instanceType);
    void ReleaseInstance(object instance);
}

Implementation of this class would be trivial for any major container on the market so framework author does not need to put it into his framework (as ’satellites’). He can happily leave it for application developer to implement using his own container or maybe even Poor Man’s DI.

So, dear reader, please support the idea of Inversion of Control (by blogging, speaking etc.) but don’t add support for it in your pet framework. It would hurt both you and me.

VN:F [1.9.13_1145]
Rating: 1.0/5 (1 vote cast)

Composing a multi-target application

The project I have been working on recently used to simple application with only two executables, a WCF service and a MVC frontend. People who worked on this project before introduced Unity as inversion of control container. To my surprise, despite using Unity, the rest of IoC infrastructure was quite decent. There was a special Composition Root project shared between WCF and MVC that configured the container with all the dependencies shared by both projects. There was no duplication with regards to IoC-related code.

Then new requirements started coming. After few weeks we ended up having a total of 15 executables, most of them being small utility console applications. Each application used only small part of solution’s components. Making each of them reference our composition root would be an overkill as I would have to ship each and every dll with these small apps.

Forgive me this lengthy preface. I just wanted to set the stage. As you certainly know right now, the problem is how should you structure the composition root so that it can be reused no only as a whole, but also in parts. I don’t suggest you should all use this solution. It is rather ‘I used this approach, what do you all think?’ kind of post.

The idea is not new in IoC container world. Just split the composition root into parts. Some good containers support this out of the box (e.g. Windsor’s installers, Autofac modules). Unfortunately Unity does not, so I had to implement it myself. That was easy. The hard problem was to decide where to put these little composition root parts. There are a couple of options, including:

  • Putting them all in one projects. This does not make any sense since because the very reason for having them was not to have to reference all the unneeded components in executables
  • Putting them in the same project as components they are responsible for
  • For each ‘normal’ project create a composition project that would now how to configure the container with it’s ‘parent project’’s dependencies

I’ve chosen the second solution. As you know, it requires referencing the container assembly from each project. Although Mark rightly warned me that thar be dragons, I decided that I will trust our project team to not disturb these dragons. This means, thou shalt not use container in any other than composition root piece of code. Period. Time will show if my faith in people was justified.

The last piece of puzzle is adding relations between composition root parts. Because I am lazy, I don’t want to specify each part I want to use. I want my composition engine to figure out that if I need reference data repositories, it should also compose in reference data session factory (we’re using NHibernate). So I added a GetDependencies method to my composition root part interface. With that in place, the composition engine can calculate a transitive closure of dependencies given only the top level ones (like the repository component) and then execute all composition root parts to configure the container. Easy, isn’t it?

Now, what do you think?

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)

On identity of dependencies

In object-oriented programming the we encapsulate responsibilities in objects. Then we build bigger and more complex objects out of smaller ones. To do so we often pass objects into another object’s constructor.The latter are then called dependencies because the former depends on them to do its job. A long time ago, in these middle ages of software engineering, we were handcrafting the code that created each and every object. We could use all the features of our programming language of choice (be it Java or C#) to control which objects are passed where. We could easily create two instances of Foo and pass one of them to Bar class and the other to Zar class. These times are long gone.

Few years ego we happily entered a Inversion of Control Container Era. Since that day we don’t have to handcraft the dependency-wiring code. It’s done for us by the container. But with the advent of these magnificent tools we lost some of the control over dependencies. Passing arbitrary object instances (not classes) as dependencies became hard. And although most of the containers support very fine-grained dependency configuration (up to single instance or factory method level), the APIs are neither easy not well-known. Moreover, using them makes your composition root (the place where you define your dependencies) code look cryptic. But is there any other way?

As you may expect, yes, there is. And it’s really simple. Just acknowledge that Inversion of Control Containers, although capable of doing miracles, don’t necessary score well when it comes to distinguishing instances of objects. It’s your job, as a programmer, to structure the solution in such a way that the container doesn’t have to deal with instances. How? Instead of having two instances of Foo create two distinct classes: FooForUsingInBar and FooForUsingInZar. They will be wrappers around Foo instances. Then, in your Bar and Zar classes you depend on either one of these wrapper classes. That’s it. Thinking why the hell would I do this?

Think about this. You have a small application that uses NHibernate to access it’s database. In the repository classes you have a dependency on NHibernate’s ISession object. Sounds reasonable, right? After a year of development (and 20 repository classes) a new requirement comes. To implement it, you have to add another database (say, a reporting database) to the solution. With the database, you have to add another 5 repositories. These will also require ISession to function. But this has to be a different instance of ISession. Now, how do you change you composition root to handle this? Will you manually specify which session to use for each repository class? Should you specify dependencies in composition root, far away from actual classes that need them? Certainly not.

It would be way better if you thought about it before and created a TransactionDatabase class that wraps ISession. Your first 20 repositories would use it. The new, reporting, repositories would requires a different class – ReportingDatabase. All you would need to do is register it in the container.

What’s the moral? Each time you add a dependency on a class or interface, think for a while if this class (or interface) has a unique identity — if, in foreseeable future, there can be one and only one instance of it in a given time and context. If so, it’s OK to depend on it. If not, think about adding a wrapper that will be unique. It can save you a lot of refactoring in the future.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)

Ewolucja przyzwyczajeń DI/IoC

Unity

Bardzo długo moim ulubionym kontenerem był Unity, mimo faktu, że dużo mądrych ludzi ze społeczności wieszało na nim psy. Dlaczego tak polubiłem Unity? Ponieważ powstawał na moich oczach. Znam go począwszy od wczesnych “zajawek” wypuszczanych przez grupę Patterns & Practices. Wcześniej nieco interesowałem się ich biblioteką ObjectBuilder, więc naturalnie moja uwaga przeszła na Unity. Byłem w stanie przeczytać i zrozumieć kod pierwszej wersji tego kontenera bez specjalnego wysiłku. Efekt tego był taki, że znam Unity jak własną kieszeń i wiem czego się po nim spodziewać.

To prawda, że pod względem ilości ficzerów Unity jest daleko w tyle za “wiodącymi” kontenerami, ale przez bardzo długi czas zupełnie mi to nie przeszkadzało.  W końcu jednak zaczęło…

Dlaczego nie Unity?

W projekcie, który aktualnie realizuję w końcu (co było do przewidzenia) pojawiła się potrzeba zastosowania kontenera DI. Było to w momencie tworzenia pierwszych testów integracyjnych. Struktura projektu oparta jest na kilku kluczowych interfejsach reprezentujących najważniejsze koncepcje, takie jak: czynność, proces (sekwencja czynności), reguła walidacji, czy reguła przepisywania. Tu pojawił się problem: chciałbym, aby rejestracja implementacji była w jakiś sposób zautomatyzowana — abym nie musiał rejestrować w kontenerze każdej kolejnej klasy. Niestety Unity (sam w sobie) nie pozwala na takie rzeczy. Czyżby czas na zmianę przyzyczajeń?

Jeśli nie Unity, to co?

Potrzebowałem czegoś, co jest w stanie zarejestrować automatycznie implementacje moich interfejsów na podstawie podanych reguł — konwencji. Wiele kontenerów obsługuje dziś takie scenariusze. W szczególności rozważałem dwa: Autofac oraz Castle Windsor. Spring.NET dyskwalifikuje niedojrzałość płynnego interfejsu konfiguracji. Wybrałem ostatecznie Autofaca. Dlaczego? Powodów jest kilka.

Po pierwsze i najważniejsze, Autofac pozwala mi zrealizować moje wymaganie. Kod konfigurujący kontener wygląda mniej-więcej tak:

private void RegisterActivities()
{
   RegisterAllTypes().Where(IsActivityType).AsSelf().SingleInstance();
}

private static bool IsActivityType(Type type)
{
   return type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IActivity<>));
}

private void RegisterRequestValidationRules()
{
   RegisterAllTypes().AssignableTo<IRequestValidationRule>().AsImplementedInterfaces();
}

Pierwsza metoda rejestruje wszystkie klasy implementujące generyczny interfejs IActivity<T> jako konkretne klasy w trybie singletonowym. Druga jest oczywiście pomocnicza. Trzecia zaś rejestruje wszystkie typy implementujace interfejs IRequestValidationRule jako imlementowane interfejsy. Prawda, że proste i eleganckie?

Po drugie, Autofac to tylko kontener. Nie posiada rozbudowanego systemu rozszerzeń (jak Castle Facilities), który, o ile aplikacja tego wymaga, może okazać się nieoceniony, jednak w moim przypadku (dosyć prosta aplikacja) tylko by zawadzał.

Po trzecie, Autofac nie posiadająca żadnych zależności. Dlaczego to takie ważne? Ponieważ mój projekt, z takich czy innych powodów, ma już podłączone (o wiele za) dużo różnych bibliotek. Nie chciałem narażać się na możliwość konfliktu wersji Castle.DynamicProxy (z którego korzystają zarówno moje biblioteki, jak i Windsor) lub log4net.

Po ostatnie (i najmniej ważne), Autofac to tylko jedna dll-ka.

Co dalej?

Zrewidowałem właśnie swoje przyzwyczajenia odnośnie kontenera. Zmieniłem Unity na Autofac. To oczywiste, ale to nie wszystko. Zmieniłem także swoje nastawienie kwestii DI w ogólności. Ta zmiana zmusiła mnie do lepszego przyjrzenia się dostępnym możliwościom, poszerzyła moje horyzonty. Wreszcie, zmiana ta uczyniła każdą następną zmianę łatwiejszą. Nowe wymaganie dla mojej aplikacji będzie można zrealizować prościej używając Castle Windsor? Proszę bardzo! Już się “przepinam”.

Nieodłączną cechą “wyzywania na pojedynek” swoich przyzwyczajeń jest uświadomienie sobie istnienia założeń, które podświadomie czynimy. W moim wypadku założeniem było korzystanie z Unity i przez kilka projektów nawet nie rozważałem innej opcji. Po “przygodzie” z Autofac, następnym razem na pewno się zastanowię. Innym przykładem nieświadomego założenia jest wykorzystanie bazy SQLowej w (entej) postaci normalnej. Czy ktoś się nad tym zastanawia? A może warto? W dzisiejszych czasach jest tyle ciekawych alternatyw…

VN:F [1.9.13_1145]
Rating: 3.0/5 (1 vote cast)

Dependency inversion patterns and the domain model

Inversion of control is constantly a hot topic. So are domain model and domain-driven design. How about combining these into one hot post? Yeah, combining posts is easy compared to combining the patterns. I will focus on particular type of inversion of control — the dependency inversion.

The problem

You are building a system. One day you encounter a new requirement stating that customers with unpaid dues should be notified by e-mail.

As a careful designer, you had decided that your business logic will be structured according to domain model pattern. When the new requirement comes, you instantly know how to implement it — just add CheckUnpaidDues method to the Customer entity.

On the other hand, as a conscious developer, you recognize that abstract concepts should not depend upon details. Put it another way, business logic (the Customer entity) should not depend upon infrastructure (the e-mail sending library). So you decide to make use of Uncle Bob’s dependency inversion principle.

Here is the initial solution.

public interface IEmailSender
{
   void SendEmail(string address);
}

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}
   public IEmailSender EmailSender { get; set; }

   public void CheckUnpaidDues()
   {
      //...
      HasUnpaidDues = true;
      EmailSender.SendEmail(EmailAddress);
   }
}

Dependency injection

It solution uses dependency injection pattern. Dependencies are being ‘injected’ into a domain model object using specialized framework — the Inversion of Control (IoC) container. This causes at least two problems.

First of all, injecting dependencies into domain objects is a technically challenging task. You have to deal with your object/relational mapping (O/RM) framework, plug into it’s instance creation process and make it use your container instead of simply new-ing up objects. This, however, can be accomplished with most O/RMs, given a skillful developer and reasonable amount of time.

The far worse problem is degradation of the model. Can you spot it right away? By adding an EmailSender field/property to the Customer entity we stated that e-mail sending mechanism is a part of customer model. It is ridiculous. Real world customers don’t carry SMTP servers in a backpack, so why should we model them that way? It is obvious that other, non domain-related, concepts are creeping into the model. We should do something to prevent this.

Double dispatch

The are some doubts (see comments under this Jimmy Bogard’s blog post) about concerning the name of this pattern, but that’s not the point. What does matter is the idea of passing a dependency as an argument to the method of domain object.

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}

   public void CheckUnpaidDuesAndNotifyUsing(IEmailSender sender)
   {
      //...
      sender.SendEmail(EmailAddress);
   }
}

What we gain here by using this pattern is a clear message stating that e-mail sending mechanism is not a part of Customer’s model, but Customer-representing entity can use it in order to send notifications.

Service Locator

We can achieve a quite similar effect using service locator pattern:

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}

   public void CheckUnpaidDues()
   {
      //...
      ServiceLocator.Current.GetInstance<IEmailSender>()
         .SendEmail(EmailAddress);
   }
}

There is a difference, however. A very big one, actually. This code hides the dependency instead of exposing it. This is what makes service locator an anti-pattern in majority of cases. As Krzysztof recently said (and I remembered)

service locator dependency is the worst of static class dependencies because it makes out class depend on possibly anything

There is, at least in case of dependency inversion, a third way (I don’t consider a service locator a solution anymore).

Domain Events

One again I will build upon great blog post series by Udi Dahan introducing a pattern called domain events. This pattern describes a solution to the problem of pushing information out of domain model without breaking it’s encapsulation. Sounds pretty useful, isn’t it? Will it enable us to send out e-mails (push data out) without introducing dependency on e-mail sender (without breaking encapsulation). Let’s try it out.
First, the pushing data out part.

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}
   public bool HasUnpaidDues { get; set; }

   public void CheckUnpaidDues()
   {
      //...
      HasUnpaidDues = true;
      DomainEvents.Publish(new CustomerHasUnpaidDuesEvent(this));
      return true;
   }
}

This model tells us that Customer entity is able to check whether there are any unpaid dues and, if so, publish that information for others to use. What are these others? An e-mail notifier, for example.

public class SendEmailIfCustomerHasUnpaidDues : IEventHandler<CustomerHasUnpaidDuesEvent>
{
   public IEmailSender EmailSender { get; set; }
   public void Handle(CustomerHasUnpaidDuesEvent @event)
   {
      EmailSender.SendEmail(@event.Subject.EmailAddress);
   }
}

It is obvious that this solution is slightly more complicated that a double dispatch one. Apart from the additional event handler class, users must also include the domain events infrastructure (I use the one Udi published, almost unmodified). Why pay the price of additional complexity?

I think that the benefit of having really clear and focused model is worth its price. Customer model no longer cares about the notification process which is not essential to the model. It focuses on that’s important — checking whether there are any unpaid dues.

This solution has, however, a downside. It can be used only in case of one-way communication. Attempts to use the event to carry the result back to the model (I have seen some) negate the publish semantics of the operation and make the whole model unreadable.

Summary

My own rule of thumb is to use domain events wherever possible (communication is, or can be, one way) and double dispatch in all the other cases. What’s yours?

VN:F [1.9.13_1145]
Rating: 5.0/5 (6 votes cast)