main

Agile software developmentApplication architectureArchitecture, PatternsBlogLanguage featuresPatterns, Software ArchThe MVC Pattern

Dependency Injection overview

February 3, 2017 — by Samuele Resca0

How-To-Use-Dependency-Injection-in-ASP.NET-MVC-6.jpg?fit=700%2C485&ssl=1

Dependency injection is a set of software design principles and patterns that enables us to develop loosely coupled code, it is also one of the most misunderstood concepts in the object oriented programming.

The Dependency injection pattern is strictly related to SOLID principles, for more information: SOLID principles using Typescript

The main purpose of the DI is the maintainability through the loose coupling technique, here is some benefits gained form the loose coupling:

Late binding

Services can be swapped with other services, late binding refers to the ability to replace parts of an application without recompiling code. For example, the following case allows developers to refers the interface IDataProvider and switch between an relational database and a NoSQL database without change the code:

Dependency injection

Extensibility and Maintainability

Code can be extended and reused, and the responsibility of each class becomes clearly defined. Finally, adding a new features  is more easy because the structure of code allows developers to understand where apply changes.

Testing

DI is an important part of supporting unit testing. Unit tests provide a rapid feedback on the state of an application, but it is only possible to write unit test when the unit can be properly isolated from it’s dependencies.

By using DI, developers have the capability to inject dependencies and mocks inside the application code to test an specific part of application without affecting others.

Here is a simple example of mocking for unit testing:

Dependency Injection containers

DI container is a software library that can automate many of the tasks involved in composing object and managing their lifetimes.
The DI containers usually expose a Resolve method: it resolves instances of arbitrary types. The DI containers know how to compose the requested type by using a sort of configuration or registration point where you map the abstractions(or interfaces) to concrete types. Finally, DI containers inherently compose object graphs by combining their own configuration with the information  from classes constructors.

DI containers configuration

There are 3 ways to configure DI containers:

  • Static file as configuration: JSON or XML store informations about the DI mapping. The advantage is that it supports replacement without recompiling, the disadvantage is the no compile-time check;
  • Code as configuration: the DI mapping is specified inside the code. The advantage is the compile-time check, the disadvantage is that it not support the replacement without compiling code;
  • Auto-registration: a set of rules (or naming convention) locates suitable components and build the mappings. The advantage is that supports replacement without recompilation and enforce conventions to make a code base more consistent. The disadvantage is that there is not compile-time check;

DI container patterns

There are some patterns that describe the right way to use DI containers:

  • Composition root: the mapping between concrete classes and interface must be composed as close as possible to the application entry point. The Composition root should be an unique location in the application;
  • Register, Resolve, Release:  The Register, Resolve and Release pattern describes how to use a DI container. The Register Resolve Release pattern states that a DI Container’s methods must be invoked in this strict sequence. The Register method register components with container. The Resolve method resolves the concrete class basing on an interface. Finally, Release method destroys the instances when they are no longer needed.

Dependency injection patterns

The Dependency injection patterns describe different ways to implement the Dependency injection inside our application. The most important is the Constructor injection pattern.

Constructor injection

The class that uses the dependency exposes a public constructor that takes an instance of the required dependency as a constructor argument. It is good practice to mark the field holding the dependency as readonly, this guarantees that once the initialization logic of the constructor has executed: the field can’t be modified. Here is an example of Constructor injection:

Constructor injection should be your default choice for DI. It addresses the most common scenario where a class requires one or more dependencies, and no reasonable local defaults are available.

Property injection pattern

When a dependency is optional we can expose a writable property that allows a client to supply a different implementation of the class’s dependency than the default.

Property injection should only be used when the class you’re developing has a good local default and you still want to enable callers to provide different implementations of the class’s dependency.

Method injection

The caller supplies the dependency as a method parameter in each method call, for example:

Method injection is best used when the dependency can vary with each method call. This can be the case when the dependency itself represents a value, but is often seen when the caller wishes to provide the consumer with information about the context in which the operation is being invoked.

Final thought

Dependency injection is the best way to enable loose coupling, an important part of maintainable code. The benefits we can see from loose coupling are not always immediately apparent, but they become visible over time during the maintenance phase.

 

Cheers 🙂

 

Agile software developmentApplication architectureArchitecture, PatternsBlogMiscPatterns, Software Arch

Feature toggling using ASP.NET

January 11, 2017 — by Samuele Resca1

ff-container-first-sql-server-basic-installer-feature-toggling-900x450.jpg?fit=768%2C384&ssl=1

Feature toggling using ASP.NET

 

Feature toggling is a technique in software development that attempts to provide an alternative to maintaining multiple source-code branches (known as feature branches), such that the feature can be tested, even before it is completed and ready for release. – Wikipedia

I have already write about feature toggling in this article. The following post describes how to implementing feature toggling using ASP.NET.

Setup the project

The following demo uses the Feature Toggle NuGet package developed by Jason Roberts . At time of writing, the package is NOT compatible with ASP.NET Core version (details here: https://github.com/jason-roberts/FeatureToggle/issues/121).

You can download and install Visual studio Community from here, and create a new project. To add the FeatureToggle package to your solution type

PM> Install-Package FeatureToggle

inside the Package manager console.

General pattern

The FeatureToggle package implements a strongly typed pattern, here’s an typical usage schema:

An strongly typed pattern avoid runtime execution errors caused by constant and magic strings. The IFeatureToggle interface defines the structure of the Toggle class, the IFeatureProvider defines the configuration location and the configuration store.

Creating Your Own Custom Toggles

To create your own custom toggle is necessary implement IFeatureToggle. You can also customize the provider behavoir by override the ToggleValueProvider property.

Using Feature Toggle

Using FeatureToggle plugin is very simple, you need create a new class in your project which extend one of Toggle classes, each Toggle class has a specific behavoir, here’s a list of default toggles. The following snippet uses the SimpleFeatureToggle class:

The SimpleFeatureToggle class reads the web.config file of the project to detect if the feature is enabled or not:

Final thought

Here’s more information about the FeatureToggle package. It is very useful to implement standard feature toggling and custom feature toggling behaviours.

For an overview on Feature Toggling, click here.

Cheers 🙂

 

Agile software developmentApplication architectureBlogPatterns, Software Arch

Continuos Delivery using feature toggle

January 11, 2017 — by Samuele Resca1

5HtnVw.gif?fit=406%2C276&ssl=1

Continuos Delivery using feature toggle

Continuos Delivery using feature toggleContinuos delivery using Feature Toggle

 A feature toggle, (also feature switch, feature flag, feature flipper, conditional feature, etc.) is a technique in software development that attempts to provide an alternative to maintaining multiple source-code branches (known as feature branches), such that the feature can be tested, even before it is completed and ready for release. – Wikipedia

Feature toggles are a powerful way of postponing the activation of features in a continuous delivery workflow.

Pros and cons of feature toggling

There are advantages to developers working using this pattern, for example: all the merge problems go away and it reduces deployment risk through canary releases or other incremental release strategies. All of this makes it easier to get new code out faster for testing and feedback.

The main disadvantages is that feature flags make the code more fragile, harder to test, harder to  maintain and less secure. In fact, feature flags  need to be short-lived, the main purpose of toggles is to perform release with minimum risk. Once release is complete toggles need to be removed.

When use feature toggling?

Feature toggling is very useful when you want to keep the production code very close to the development version, when the business isn’t ready for the feature to be enabled or when you want perform an canary release of your code.

Important: do not use feature toggling to enable code that is not complete. Feature flags introduces a lot of complexity in your code.

Feature toggle components

Feature toggling pattern is usually implemented by three different components:

  • Toggle point: is the component which call the toggle router;
  • Toggle router: contains the logic to check if a certain toggle point is active or not. Toggle router reads toggling configurations to detect features or simply detect an Toggle Context. For example a special cookie or HTTP header.
  • Toggle configurations: contains the informations about the active/deactivate toggle points. Usually, toggle configurations, are environment-specific;

Categories of toggles

Feature toggles can be categorised by using different params: the longevity of the feature and how dynamic the toggling decision must be.

  • Release toggles:  separate feature release from code deployment. Release toggles allow codepaths  to be shipped to production as latent code;
  • Experiment toggles:  perform multivariate or A/B testing. This technique is commonly used to make data-driven optimizations to things such as the purchase flow of an e-commerce system, or the call to action wording on a button. An Experiment Toggle needs to remain in place with the same configuration long enough to generate statistically significant results;
  • Ops toggles:  ops toggles will be relatively short-lived – once confidence is gained in the operational aspects of a new feature the toggle should be retired;
  • Permissioning toggles:  change the features or product experience that certain users receive. For example we may have a set of “premium” features which we only toggle on for our paying customers;

Toggle configurations

There are different way to change and manage feature toggle flags:

  • Compiled: the flag value is written in the code, hardcoding doesn’t allow dynamic re-configuration of a toggle;
  • File: you can read toggle configurations inside a structured file, for example a JSON file, you can now re-configure a toggle by simply changing that file rather than re-building application code itself;
  • Parametrised: the toggle configurations are passed as command-line arguments or query string parameters. You need to pass the configurations every time;
  • Database: you can store configurations inside a database. Usually, it is combined with some form of admin UI which allows system operators, testers and product managers to view and modify Features Toggles and their configuration;

Feature toggling in practice

This article shows how to implement Feature toggling using ASP.NET.

Conclusion

Feature toggling is very useful technique in the continuos delivery stack. I suggest to use it with care, because each Toggle introduces technical debt inside our code.

Here are some useful link about feature toggling:

Martin Fowler – Feature Toggle

Feature Toggles are one of the worst kinds of Technical Debt

Decoupling Deployment and Release- Feature Toggles

Cheers 🙂