Tag Archives: simple

No Events: ReactiveUI Windows Forms MVVM-Style


designed using http://viperneo.github.io/winforms-modernui/

This is the next post in the series, looking first at Reactive Extensions (RX) to simplify writing Windows Forms UI logic, then using a viewmodel shared between a WPF gui implementation and a rewritten WinForms version using ReactiveUI, stopping at a short article on testing the viewmodels.


ReactiveUI News

ReactiveUI API has been quite volatile for the last year, and this series is in need of an update1. A CodeProject author gardner9032 published a nice teaser article, showing the ReactiveUI mechanism for writing simplified Viewmodel-View bindings 2, which serves as primary trigger for this post.

There’s plenty of news and updated articles on Paul Betts’ log, providing a good resource for updates on the API. Phil Haack’s blog is also a superb resource for explanations and commentaries on the use of ReactiveUI in real-world applications.

The ReactiveUI project is quite active, as the community seems to have grokked the jist of it, while the list of supported platforms has become more than convincing.

Getting rid of events

The enabling feature of ReactiveUI is writing declarative UI glue code, and if the viewmodels are based on Reactive Extensions, then declarative C# style can be used throughout the project. The previous ReactiveUI Windows Forms examples converted an event sequence into an observable sequence of values. In this example, that will be accomplished conveniently by the ReactiveUI WinForms lbrary. The viewmodels also contained some imperative code. For this article, the viewmodels will not be reused from the previous articles, but written from scratch.


s. code

The viewmodel’s task is the same: something is ticking in the background, while words are counted in the input text asynchronously, and the calculation is throttled to 0.5 seconds. The viewmodel boilerplate is simplified using ReactiveUI.ReactiveObject.

Output (read-only) properties

The ReactiveUI-way of creating output properties is through ObservableAsPropertyHelper.

private readonly ObservableAsPropertyHelper<string> backgroundTicker;
public string BackgroundTicker
        return backgroundTicker.Value;

The constructor of the viewmodel receives an IScheduler for scheduling on the correct thread, and an IObservable, which will be a stream of input from the view. Observe the ToProperty helper:

public MyViewModel(IScheduler scheduler, IObservable<string> input)
        .Select(_ => DateTime.Now.ToLongTimeString())
        .ToProperty(this, x => x.BackgroundTicker, out backgroundTicker);

Word counting logic is implemented in a similar fashion by transforming the incoming stream of strings.


s. code

To remove yet more boilerplate code, WinForms Form specialization implements the ReactiveUI.IViewFor interface. This allows for largely simplified run-time and compile-time checked bindings, avoiding using strings for property names. The implementation is straightforward, and pays off once the views become more complex than this example:


public MyViewModel VM { get; private set; }

object IViewFor.ViewModel
    get { return VM; }
    set { VM = (MyViewModel)value; }

MyViewModel IViewFor<MyViewModel>.ViewModel
    get { return VM; }
    set { VM = value; }


None of the controls in the designed WinForm have wired events or bindings set from the designer. The glue code is reduced to instantiating the viewmodel …

VM = new MyViewModel(
    new System.Reactive.Concurrency.ControlScheduler(this),
    this.WhenAnyValue(x => x.inputBox.Text)

… and declaring the bindings3 4.

this.Bind(VM, x => x.BackgroundTicker, x => x.tickerBox.Text);
this.Bind(VM, x => x.WordCount, x => x.wordCountBox.Text);



  1. See ReactiveUI Design Guidelines
  2. see article @CodeProject
  3. The ReactiveUI WinForms implementation seems not to support fully read-only fields using default bindings yet, hence an empty setter in the viewmodel
  4. The scheduler is from Windows Forms helpers

ris – a lightweight cross-platform resource compiler for c++ projects

Why a resource compiler in the 21st century?

Starting a c++ project that will potentially need static string resources (i.e. Lua scripts) makes one search for an easy way to embed large strings in an executable. There are many ways of including static resources, but there seems to be no simple but robust, platform-independent way 1. For fast prototyping and one-shot projects, I’d like to have lightweight, minimum-configuration and install solution to the problem of embedding binary resources without having to use a large framework.

Premake, my favourite light-weight meta-build system contains a number of Lua scripts in its binary. These are embedded using a Lua script into a simple array of C-string constants. This is the simplicity that in my view should be strived for. ris is an attempt to do something similar for general c++ projects with a possibility of embedding binary blobs.

ris – cross-platform resource compiler for c++

The project (ris@github) is in its infancy, but seems already to be usable. Here’s a preview:

Defining and compiling resources

ris <path_to>/<resources>.json

with an input file as this self-explaining one:

    "namespace" : "test",
    "header" : "acceptance_test/resource.h",
    "source" : "acceptance_test/resource.cpp",
    "resources" : [
            "name" : "string_test",
            "source_type" : "string",
            "source" : "plain text"
            "name" : "binary_file_test",
            "source_type" : "file",
            "source" : "test.bin"

will generate two c++11 files to include in your project, enabling easy resource retrieval:

std::string res = test::Resource::string_test();


std::string res = test::Resource::Get("string_test");

Update 30.07.2015: now resources can be defined more concisely in YAML. A minimal resource definition in YAML looks like the following:

header: "res.h"
source: "res.cpp"

    compression: "LZ4F"
    name: "some_text"
    source: "some text"
    source_type: "string"

Enumerating the resources

Resource keys in the compiled resource can be enumerated passing a callable to GetKeys:

std::vector<std::string> keys;
test::Resource::GetKeys([&keys](char const* key){


Using an optional compression library bundle, adding a compression property to a resource description enables transparent (de)compression:

"compression" : "LZ4HC"


updated 24.11.2014:
ris now uses text resources generated and bootstrapped by its own early version. The goal is to make The code generator is customizable. The default template can be seen in template.json, and the generated header in template.h. The generation sequence can be seen in ris.cpp.

Using the second parameter to ris, it’s possible to override strings in the generator template. See an example below.


updated 27.11.2014:
One such customization is available in template_cpp03.json, where the C++11 constructs are replaced with generateable C++03 constructs.

To generate the resources using the C++03 template:

ris my_template.json template_cpp03.json

Why C++?

Such code generator as ris could most probably be developed more rapidly using any other programming language with a huge framework and a ton of libraries behind them. My personal preference for certain kinds of small projects lies in the area of self-contained single-binary/single-file executables or libraries, such as Lua. Lua is the primary motivation for this project, as it is itself a compact library for building flexible and extensible prototypes and tools. ris can act as a bootstrapping component to embed resources for building specialized shell-scripting replacements, i.e. for massive scripted file operations.



There is a number of paths this project can take from here. Features, such as robustness, performance or flexibility could all be addressed, but most probably ris will be shaped by its usage or absence of such.

The quest for a c++ Dependency Injection Container library. Part 3, beginning dicpp

Dependency Injection + C++ = dicpp

The first article introduced the example problem – an almost trivial example for dependency injection. One of the implementation classes is mocked within a test to show the resulting implementation configuration flexibility.

Another library in the quest is dicpp. It is somewhat similar to sauce with little twists, hence it required some trial and error to get right after sauce. Dicpp configures the dependencies in code and allows configurable lifetime scopes.


Modules are, again, similar to sauce’s modules, as they can be simple functions for registering the bindings of interfaces to implementations.

The library uses a slightly intrusive macro that puts a special typedef in the class’ declaration. One constructor is supported and should be split into declaration and definition. The macro for the renderer looks as follows:

class DicppKeyRenderer : public IRender {
	DI_CONSTRUCTOR(DicppKeyRenderer,(std::shared_ptr< IGetKeyValue > m));

Without changing the existing factory, the default implementations are used:

DicppKeyRenderer::DicppKeyRenderer(std::shared_ptr< IGetKeyValue > m) :
	pimpl ( NewKeyRenderer(m) ) { }

The module with the bindings looks as follows (dicpp_module.cpp):

void dicpp_module( di::registry& r ) {
	r.add( r.type< IGetKeyValue >().implementation<DicppJsonDecoder>() );
	r.add( r.type< IRender >     ().implementation<DicppKeyRenderer>() );

Mock and the Singleton scope

To set the mock expectations on an instance of a dependency, one needs to obtain a pointer to that dependency. Once again, the mock implementation of an interface is done via googlemock:

class MockModel : public IModel {
	MOCK_METHOD0(Get, std::string());

To obtain the same instance of the mocked IModel as which gets resolved automatically, one can use a dedicated scope, such as the singleton scope. The mock is added to the module in the singleton scope:

void mock_module( di::registry& r ) {
	r.add( r
		.in_scope<di::scopes::singleton>() )

Configuring the injector


The injector is the container of bindings that gets configured by adding modules:

di::injector inj;
inj.install( dicpp_module );
inj.install( mock_module );

Configuring the mock

With the modules “installed” in the injector, the singleton mock instance can be obtained:

auto mock_model = inj.construct_ptr< IModel >();

MockModel* mock_model_ptr = dynamic_cast< MockModel* >(mock_model.get());
ASSERT_TRUE( mock_model_ptr );

EXPECT_CALL(*mock_model_ptr, Get())
	.WillRepeatedly(Return("{ \"a\" : 1 , \"b\" : 2 }"));

Logging in dicpp

An interesting feature in dicpp is logging of the library activity. The feature can be overridden or turned off via macro definition. The construction of dependencies can be traced, such as here, slightly shortened :

[DICPP]: Registering: IGetKeyValue with implementation: DicppJsonDecoder in scope: di::scopes::no_scope
[DICPP]: Registering: IModel with implementation: MockModel in scope: di::scopes::singleton
[DICPP]: Registering: MockModel with implementation: MockModel in scope: di::scopes::no_scope
[DICPP]: Constructing: di::type_key<IModel, void>
[DICPP]: Provided type: di::type_key<IModel, void>
[DICPP]: Singleton: constructing: di::type_key<IModel, void>
[DICPP]: Generic constructing IModel with implementation: MockModel
[DICPP]: Completed constructing: di::type_key<IModel, void> with address: 0x7fd0b2600e40
[DICPP]: Singleton: returning existing: di::type_key<IModel, void>

As one can see, two bindings are registered for one implementation – the interface and implementation can be resolved at later time.


The rest of the example is very similar to the first and the second parts of the quest:

auto renderer = inj.construct_ptr< IRender >();
ASSERT_EQ( "a,b", renderer->Render() );

Although the library is very similar to sauce, the binding definition language doesn’t read as fluently as that of wallaroo or sauce. Further articles may elaborate on the outstanding features of either library.

Source: https://github.com/d-led/test-ioc-cpp


05.11.2014: Removed boost<->std shared_ptr conversions, as dicpp has been updated in the meanwhile

More to come…

The quest for a c++ Dependency Injection Container library. Part 2, some Sauce


In Part 1 I have started with a list of C++ dependency injection libraries, and sketched an example problem, solved and tested with the help of Wallaroo. For the second part, Hypodermic should have been in focus, but unfortunately, no version compiled out of the box on MacOS with Clang 1. Hence, the article is about sauce, an inspiration from google-guice.

Dependency Injection using sauce

A little repetition, the example problem contains of 3 interfaces with a linear dependency graph of the implementations. Not to repeat the implementations, and not change the structure of the existing code, simple factories for the default implementations have been exposed, but not the concrete types in the headers, i.e. for the default renderer implementation:

std::shared_ptr< IRender > NewKeyRenderer(std::shared_ptr< IGetKeyValue > model) {
	return std::make_shared<KeyRenderer>(model);


Simplified, the sauce solution looks as follows. Unlike in Wallaroo, in sauce, the implementations do not need to derive from a common “dependency” class. Any type can be bound to any derived class. The implementation of a renderer for the sauce example just adds a delegation to the original implementation 2:

class SauceKeyRenderer : public IRender {
	SauceKeyRenderer(std::shared_ptr< IGetKeyValue > m) :
	pimpl ( NewKeyRenderer(m) )
	{ }

	virtual std::string Render() {
		return pimpl->Render();

 	std::shared_ptr< IRender > pimpl;


Modules are containers of bindings of interfaces to their implementations. The easiest way to define a module is to provide a function with the signature void (* module)(sauce::Binder &).

Here’s the self-explaining module:

void render_module(sauce::Binder& b) {

Once again, obviously, the type doesn’t have to leak outside the module due to inversion of control.

Note that the IGetKeyValue dependency of SauceKeyRenderer is injected via the constructor parameter, enabling automatic dependency resolution at later time.


Instances of the bound interfaces are obtainable from injectors, which can be constructed from a collection of modules:

sauce::shared_ptr<Injector> injector = Modules()

Resolving the dependencies

The hello-world example of resolving the dependencies is one simple line:

sauce::shared_ptr<IRender> renderer = injector->get<IRender>();

In this case, SauceKeyRenderer will get resolved and two other dependencies will be automatically instantiated and injected (see test_sauce.cpp).

Mocking and singletons

Sauce allows for different lifetime models of the interface instances. Singletons are possible with the concept of scoped injectors, in which, the instances are shared.

For googlemock getting the resolved instance is crucial, since the expectations are bound to an instance of the mocked class. With automatic dependency resolution and no hacks, the interface IModel would resolve to a new instance in the test. Hence, unless a way to use the shared instance lifetime inside the test is found, the mock is implemented trivially without googlemock.


This article is once again a short intro into the paradigm of another Dependency Injection library sauce. A more elaborate intro can be read in sauce’s tutorial test suite.

Source: https://github.com/d-led/test-ioc-cpp

More to come…

  1. To do in 2014
  2. Efficiency and overhead are not considered in the first place.

The quest for a c++ Dependency Injection Container library. Part 1, Wallaroo Introduction


Given the static nature of the C++ type system, the lack of reflection and a platform-independent ABI in native C++, dependency injection doesn’t seem to have fallen into fashion in C++ projects 1. It might be that using the right tool for the right job diminishes the need for dependency injection containers for C++. Nonetheless, I find it worth digging into today’s offer of different libraries. Along the way, several other technologies will shine.


The resulting code will be constantly updated at https://github.com/d-led/test-ioc-cpp.

The project is expected to compile and run on many desktop platforms with a c++11 compiler. Hence, the makefiles are made with premake and a small helper library.

Mocks are useful when you use dependency inversion, hence the googlemock library will be used for demonstration purposes. Currently, the whole project is a single googletest executable, which is run after each compile.

Some makefiles and a Visual Studio solution are checked in, but can be generated from the premake script anytime.

The plan

The plan is to introduce each DI library superficially at first, and then to dig for feature differences, common patterns and perhaps applicability suggestions. The quest over the available libraries might take some time. The first intent is to give hello world examples of C++ DI libraries in action.

Linux builds and test runs will be performed automatically at https://travis-ci.org/d-led/test-ioc-cpp.

The libraries

A note on memory management

The Single Responsibility Principle is ingrained in all of the Dependency Injection libraries, as the instances are managed via smart pointers, which take up the responsibility of memory management.

Example architecture

An artificial, simple, decoupled architecture is used in the example. The interfaces are as follows:

struct IRender {
	virtual std::string Render() = 0;
	virtual ~IRender() {}

struct IGetKeyValue {
	virtual size_t Count() = 0;
	virtual std::string GetKey(size_t pos) = 0;
	virtual std::string GetValue(std::string const& key) = 0;
	virtual ~IGetKeyValue() {}

struct IModel {
	virtual std::string Get() = 0;
	virtual ~IModel() {}

The names might change during the quest. The expected dependencies are as follows: the renderer needs a model, which is a key-value pair collection, which might be decoded from some kind of data_source, which is here simply a string.


To start with the quest, let’s look at Wallaroo. This has been the first library that I’ve considered using, and have already written a little walkthrough: lul.

The library has a rather exotic DSL for a DI library, however, it seems to be very well suited for communicating the concepts.

The objects (components) are created within a so-called catalog and have string IDs. When all the necessary objects have been created, they can be wired together with a DSL in the form:

within the catalog, use component_1 as dependency_1 of component_2.

Components == Parts

Let’s see how the components that are usable within Wallaroo are defined. A drawback of Wallaroo can be seen from the start, namely that the components have to be defined intrusively – they have to derive from wallaroo::Part:

class WallarooKeyRenderer :  public wallaroo::Part , public IRender { ... };

The drawback can be somewhat overcome by using the Bridge pattern with composition when refactored. The first implementation here is fully dependent on wallaroo::Part.

The library allows static registration, hence there is no need to expose the type or even a manually written factory of WallarooKeyRenderer:

WALLAROO_REGISTER( WallarooKeyRenderer );

is the registration macro.


Dependencies are called wallaroo::Collaborators. These can be private members:

wallaroo::Collaborator< IGetKeyValue > model;

and must be initialised in the constructor:

		model( "model", RegistrationToken() )  { }

Then, if wiring the objects succeeds, the collaborators are usable as smart-pointers:

... model->GetKey(pos);

A nice feature in Wallaroo is that it supports constructor parameters. Another one – an initial support for loading plugins from DLLs exists. The configuration of catalogs: instances of objects and their wirings can be loaded from XML or JSON.

Full source: wallaroo_render.cpp

Instantiating objects

There are two implementations of the interfaces: a JSON decoder (using the lightweight single-header picojson library) and a renderer described above. The model can be simply mocked using GMock.

Inside the test (test_wallaroo.cpp) the model can be instantiated as follows.

Given the mock implementation:

class MockModel : public IModel, public wallaroo::Part {
	MOCK_CONST_METHOD0(Get, std::string());

one can now instantiate the mock inside the test and set expectations using the GMock DSL:

catalog.Create("mock model","MockModel");
std::shared_ptr<MockModel> mock_model = catalog["mock model"];
ASSERT_TRUE( mock_model.get() );
EXPECT_CALL(*mock_model, Get())
	.WillRepeatedly(Return("{ \"a\" : 1 , \"b\" : 2 }"));

The other objects are instantiated in the fixture:

catalog.Create("renderer", "WallarooKeyRenderer");



using an example of a factory with inverted control, in case one doesn’t want to let out strings that represent types, but cannot be checked at runtime:

void CreateDecoder(std::string const& name,wallaroo::Catalog& catalog)
	catalog.Create(name, WallarooJsonDecoder);

That way you neither leak the implementation type, neither its typename string.

Wiring dependencies

Now that the objects are instantiated, they can be wired in code:

	use("mock model").as("data_source").of("decoder");

A feature I enjoy in Wallaroo is that you can rewire the dependencies at runtime without creating new objects. That might get you some weird runtime dependencies if your code becomes messy, but if you take care of the quality, that feature might get handy.

When everything is wired up, the test is concluded with

ASSERT_EQ( "a,b", renderer->Render() );


Wallaroo is an easy to use header-only library, resembling in its use the Multiton Pattern. If instances of the dependencies can be given unique ids, there may be multiple implementations of the same interface, and if the dependencies should be rewired at runtime, wallaroo is a perfect choice.


05.11.2014: new wallaroo metaphors, +di, +infectorpp

More to come…

  1. Alternative areas: COM & .NET
  2. Can’t compile out of the box on clang yet

yet quicker start for a c++ project

The simplest way to try out some c++ concepts on your machine is the built-in build support of some ‘smart’ text editors, such as Sublime Text or SciTE. However, if you want to start quickly, but be able to grow the project from that one small seed, you’d probably want to have SCM set up.

To start cross-platform c++ projects I usually use git and premake. For premake I’ve set up a couple of quickstart scripts that implement some code organization conventions I usually follow. That project still requires one to set up a git directory, add a submodule, edit a premake4.lua file, write the first code file. How about automating these tasks as well. Every developer writes own support shell scripts, here’s one: new_cpp.sh that doesn’t do much – just what is described above. Considering, you have copied it somewhere where it’s executable globally, here are the steps:

  1. new_cpp.sh project_name → make the directory, init a git repo, add the premake submodule, the first source file and the premake4 build meta-configuration.
  2. cd project_name
  3. premake4 gmake → generate, makefiles, could be vs*, xcode*, too.
  4. make -C Build → build to see if everything is set up.

You can now start growing your code from project_name.cpp.