.NET tanker & tips

.Net, jQuery og andre nørdede emner

You are not Mozart - get help with composition

januar 07
by steffen 7. januar 2019 15:21

Mozart In one of my previous blog posts I wrote about dependency injection and why this should be a core principle when designing software architecture. The benefits from injecting dependencies into the classes who need them are many. One of the most important benefits is that your code will be loosely coupled, which makes the code flexible and make it much easier to reuse the code in multiple scenarios. A great benefit from loosely coupled code is also, that the code will be much easier to unit test. This allows us to assert that the code behaves as in the way that it was intended.

The most common way of implementing DI is by using constructor injection. This means that each class will take all their dependencies as an argument in the constructor. This pattern ensures that it is not possible to create an instance of a class, if you do not provide all the required dependencies. You can also inject dependencies by exposing the class dependencies through properties, allowing the client to initialize the dependencies. Personally I am not a fan of this approach, since this put the responsibility of initializing the correct dependencies on the client, which may or may not have the knowledge on the inner workings of the class. This can result in runtime exceptions, if a method is called, which depend on a uninitialized dependency.

When using DI the classes needed for a software system to work, must be build as close to the entry point of the system as possible. In a console application this would be in the Main method and in a MVC application it should be before the controller is executed. This is easily accomplished by using a DI framework (e.g. StructureMap). When using a DI framework, which I highly recommend, it will be responsible for creating the entire object graph, required for the system to function. The DI framework will analyze the dependencies of you code and based on convention and/or configuration it will spin up the required objects and inject them into the program.

A great example of a mature and well functioning DI framework is StructureMap (soon to be called Lamar). One of the cool features in StructureMap is that it has some default conventions, that allows you to get up and running with fewer lines of code. The main convention is that, unless specified in the composition root (the configuration method of StructureMap), for an interface called IFoo it will look for a concrete class called Foo. As such StructureMap rely on the normal naming convention where the name of an interface always start with an "I". This convention means that StructureMap will automatically map all interfaces to the respective concrete implementations, without you writing a single line of code.

Obviously most scenario will not consist exclusively of interfaces and classes with this naming relation. For all the other interface/class combinations, you must define which concrete classes must be used for which interfaces. An example could be that you have a ICar interface and you want StructureMap to inject an instance of the Jeep class (which implements the ICar interface). This is easily done with a short line of code in the configuration of StructureMap.

public class DefaultRegistry : Registry {

public DefaultRegistry() {

            Scan(

                scan => {

                    scan.TheCallingAssembly();

                    scan.WithDefaultConventions();

                });

            For<ICar>().Use<Jeep>();

        }

    }

The DefaultRegistry class and the code in the constructor, is responsible for creating the object graph. This is called the "composition root" and in a more complex application this class will be significantly bigger as the entire object graph of the application is defined here. One of the strong points by having all the configuration centralized in the composition root, is that you always know exactly where the object tree is constructed.

When using StructureMap to control the composition root, an added benefit is that it integrations seamlessly into most application types. When installing StructureMap from NuGet, you can almost certainly find a flavor of StructureMap that suit you application type. This means that as soon as StructureMap has been installed, it will be "plugged into" your application pipeline, ensuring that the composition root is called whenever the application needs an object graph.

Tags:

Dependency Injection | General

Let StructureMap be your Alfred

juli 11
by steffen 11. juli 2018 14:03

Alfred Pennyworth - http://www.mothershiptoys.com/hot-toys-mms236-batman-armory-with-bruce-wayne-and-alfred-pennyworth.html

In my previous post I addressed the concept of dependency injection (DI) and what the advantages are by using this technique. In this post we will look at little closer at some concrete examples on how to use StructureMap to help resolve dependencies (injecting the correct objects to each class that has an dependency on an interface). 

Like all good super heroes a coder need a tech saavy helper, that make sure the hero has all the tools needed for the job. James Bond has Q, Batman has Alfred and .NET has StructureMap. 

What is StructureMap?

StructureMap is a DI framework, that rely heavly on conventions to resolve the dependecies a class has. It is preferable to choose the convention based approach, in order to save as much time on the tedious configuration. The main convention in StructureMap is that it rely on the name of the interfaces and classes to "connect the dots". The common naming convention is to prefix all your interfaces with "I" and StructureMap leverages this convention.

If a class is depending on an interface IBar, StructureMap will look for a concrete class called Bar. This means everytime you have a one to one realationship between an interface and a class (IBar to Bar), this is handled automatically, without any extra configuration. There will of course always be some configuration - especially if the dependecies does not fall into the default convention - we'll take a look at this next.

Configuring StructureMap in ASP.NET MVC

I'll use an ASP.NET MVC project as an example. First we have to install StructureMap in the solution. This is easiest done from the package manager console:

Install-Package StructureMap.MVC5

At the time of writing I'm running MVC version 5 and hence is using the package targeted this version. After all the dependecies has been installed a new folder called "DependencyResolution" has been created in the root of the web application project. In this folder open the DefaultRegistry.cs file:

public class DefaultRegistry : Registry {
        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
        }
    }

The body of the call to Scan is where the container is configured. The most important part here is to configure which assemblies StructureMap should search when resolving a dependency. The call to scan.TheCallingAssembly() means that StructureMap will be able to resolve all classes in the current assembly (all classes in the web project in this case).

Usually the solution will consist of more than one project. This could be a class library with all the domain classes. In this case StructureMap must be configured to include these assemblies when resolving a dependency. Let's illustrate this with an example.

Including assemblies

In the solution on the right, there are two projects: a class library called Domain, which contains an interface and a concrete implementation of the interface, and a MVC project. Assuming that the MVC project has a reference to the Domain project and uses an instance of the IFoo interface, we must set up StructureMap to find the correct assembly and resolve the correct concrete implementation of IFoo. 

The controller could look something like this:

public class HomeController : Controller
    {
        private IFoo _foo;

        public HomeController(IFoo foo)
        {
            _foo = foo;
        }

        public ActionResult Index()
        {
            return View();
        }
    }

At this moment StructureMap does not know about the Domain assembly and will throw an exception (a very confusing "Class has not parameterless constructur" error, which does not indicate that it is a StructureMap issue). In order to get StructureMap to inject an instance of Foo, when the controller is created and is requires an instance of IFoo, StructureMap must be configured to look in the Domain assembly. This is done fairly simple by telling StructureMap to add the assembly containing the required classes and interfaces. There is a few ways to do this, but the two most simple ways are adding it by the assembly name or pointing to a type (ie. class, interface) in the assembly. Just remember that if you change the assembly name/move the type to another assembly, StructureMap will not be able to find the correct assembly needed for the dependency injection.

The code for configuring StructureMap to look in the Domain assembly in the small test project looks like this (code using the method pointing to a type is commented out):

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
        }

When conventions doesn't cut it

Obviously the example above is very basic, but it really get you off the ground in a hurry and let's you focus on the code instead of the configuration. When you run into scenarios that does not fit into the common StructureMap conventions a little configuration is needed. But fortunately the good guys and girls at StructureMap made sure that this is very easy to set up using the fluent API.

Let's assume that we have a concrete implementation of IFoo that is called Bar. Obviously this does not match the StructureMap conventions (IFoo -> Foo) and in order for StructureMap to handle this, we must configure this. The configuration is quite simple and readable and must be added after the call to Scan. The syntax is For<TheInterfaceName>().Use<TheTypeYouWantInjected>();. It looks like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
                For<IFoo>().Use<Bar>();
        }

Now each time a class requires a concrete type of IFoo StructureMap will inject an instance of Bar. You can even add logic in the configuration, if the application have different dependencies in different situations. This could look something like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
            if (someBoolValue)
            {
                For<IFoo>().Use<Bar>();
            }
            else
            {
                For<IFoo>().Use<Foo>();
            }
        }

I have used this approach with a webshop where there were different business rules (ie. VAT, tax, delivery) depending on which country the customer was from. 

Tags: , ,

ASP.NET | ASP.NET MVC | Dependency Injection

Let StructureMap be your Alfred

juli 11
by steffen 11. juli 2018 14:01

Alfred Pennyworth - http://www.mothershiptoys.com/hot-toys-mms236-batman-armory-with-bruce-wayne-and-alfred-pennyworth.html

In my previous post I addressed the concept of dependency injection (DI) and what the advantages are by using this technique. In this post we will look at little closer at some concrete examples on how to use StructureMap to help resolve dependencies (injecting the correct objects to each class that has an dependency on an interface). 

Like all good super heroes a coder need a tech saavy helper, that make sure the hero has all the tools needed for the job. James Bond has Q, Batman has Alfred and .NET has StructureMap. 

What is StructureMap?

StructureMap is a DI framework, that rely heavly on conventions to resolve the dependecies a class has. It is preferable to choose the convention based approach, in order to save as much time on the tedious configuration. The main convention in StructureMap is that it rely on the name of the interfaces and classes to "connect the dots". The common naming convention is to prefix all your interfaces with "I" and StructureMap leverages this convention.

If a class is depending on an interface IBar, StructureMap will look for a concrete class called Bar. This means everytime you have a one to one realationship between an interface and a class (IBar to Bar), this is handled automatically, without any extra configuration. There will of course always be some configuration - especially if the dependecies does not fall into the default convention - we'll take a look at this next.

Configuring StructureMap in ASP.NET MVC

I'll use an ASP.NET MVC project as an example. First we have to install StructureMap in the solution. This is easiest done from the package manager console:

Install-Package StructureMap.MVC5

At the time of writing I'm running MVC version 5 and hence is using the package targeted this version. After all the dependecies has been installed a new folder called "DependencyResolution" has been created in the root of the web application project. In this folder open the DefaultRegistry.cs file:

public class DefaultRegistry : Registry {
        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
        }
    }

The body of the call to Scan is where the container is configured. The most important part here is to configure which assemblies StructureMap should search when resolving a dependency. The call to scan.TheCallingAssembly() means that StructureMap will be able to resolve all classes in the current assembly (all classes in the web project in this case).

Usually the solution will consist of more than one project. This could be a class library with all the domain classes. In this case StructureMap must be configured to include these assemblies when resolving a dependency. Let's illustrate this with an example.

Including assemblies

In the solution on the right, there are two projects: a class library called Domain, which contains an interface and a concrete implementation of the interface, and a MVC project. Assuming that the MVC project has a reference to the Domain project and uses an instance of the IFoo interface, we must set up StructureMap to find the correct assembly and resolve the correct concrete implementation of IFoo. 

The controller could look something like this:

public class HomeController : Controller
    {
        private IFoo _foo;

        public HomeController(IFoo foo)
        {
            _foo = foo;
        }

        public ActionResult Index()
        {
            return View();
        }
    }

At this moment StructureMap does not know about the Domain assembly and will throw an exception (a very confusing "Class has not parameterless constructur" error, which does not indicate that it is a StructureMap issue). In order to get StructureMap to inject an instance of Foo, when the controller is created and is requires an instance of IFoo, StructureMap must be configured to look in the Domain assembly. This is done fairly simple by telling StructureMap to add the assembly containing the required classes and interfaces. There is a few ways to do this, but the two most simple ways are adding it by the assembly name or pointing to a type (ie. class, interface) in the assembly. Just remember that if you change the assembly name/move the type to another assembly, StructureMap will not be able to find the correct assembly needed for the dependency injection.

The code for configuring StructureMap to look in the Domain assembly in the small test project looks like this (code using the method pointing to a type is commented out):

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
        }

When conventions doesn't cut it

Obviously the example above is very basic, but it really get you off the ground in a hurry and let's you focus on the code instead of the configuration. When you run into scenarios that does not fit into the common StructureMap conventions a little configuration is needed. But fortunately the good guys and girls at StructureMap made sure that this is very easy to set up using the fluent API.

Let's assume that we have a concrete implementation of IFoo that is called Bar. Obviously this does not match the StructureMap conventions (IFoo -> Foo) and in order for StructureMap to handle this, we must configure this. The configuration is quite simple and readable and must be added after the call to Scan. The syntax is For<TheInterfaceName>().Use<TheTypeYouWantInjected>();. It looks like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
                For<IFoo>().Use<Bar>();
        }

Now each time a class requires a concrete type of IFoo StructureMap will inject an instance of Bar. You can even add logic in the configuration, if the application have different dependencies in different situations. This could look something like this:

public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
					scan.With(new ControllerConvention());
                    //scan.AssemblyContainingType<Foo>();
                    scan.Assembly("Domain");
                });
            if (someBoolValue)
            {
                For<IFoo>().Use<Bar>();
            }
            else
            {
                For<IFoo>().Use<Foo>();
            }
        }

I have used this approach with a webshop where there were different business rules (ie. VAT, tax, delivery) depending on which country the customer was from. 

Tags: , ,

ASP.NET | ASP.NET MVC | Dependency Injection

Dependency Injection Principle and the Geekmobile

marts 17
by steffen 17. marts 2017 06:28

Almost everyone in the development environment agrees that Dependency Injection (DI) is a corner stone of good software design. When implemented correctly it gives quite a few advantages to the code. The biggest advantages are that the code becomes easier to unit test and that the code will be more loosely coupled. However the concept of Dependency Injection can be a little hard to grasp at first. I will therefore try to first in explain in it general terms and afterwards provide some code examples.

There are two rules to the Dependency Injection Principle:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions
  • Abstractions should not depend on details. Details should depend on abstractions

Let's take a look at what that means. The first rule means that each class should have as few references (none, if possible) to concrete classes as possible. Not to say that a class can't use a concrete class, but it is a clear code smell if there is. Instead you should use abstractions ie. interfaces or abstract classes where possible. The use of interfaces makes the code loose coupled, hence making it much more flexible and handling changing requirements much easier.

The basic idea that, in order to prepare your code for future changes, it should be structured in a way that will make changes easy, without causing a tsunami of changes other places in your code. This is commonly referred to as loose coupling.

The second rule, means that you have to design your code, so that if you change something in your concrete class, it must not change the outcome from what the abstraction expects.

This is best illustrated with an example (inspired by Vincent Ramdhanie's answer on SO). When I get into my car, all the controls (eg. pedals and steering wheel) are abstractions (or interfaces if you will) between me and the mechanics of the car. I understand the abstractions and by using the controls I can control the car: when I press the right pedal the car will accelerate and when I press the middle pedal (or left if you're not driving a stick), the car will decelerate.

Steering wheel from the geek-mobile

Steering wheel from the Geekmobile (image from xboxfreedom.com)

If we change some of the implementation details (eg. changing the engine in the car), you cannot change the abstractions. For instance you cannot swap the pedals, so that the brake pedal is now on the right. The same rules should apply to you code. If you have a calculator class, which implements an interface with a method called Add, you can change the code in the concrete implementation, but never in a way that it changes the abstraction (eg. dividing instead of adding). This is of course a very simple example and you might think your code is much more complex. That might be true, but this is one more reason for you to try to design your code to be as simple and loosely coupled as possible. If you design your classes with the Single Responsibility Principle in mind, your interfaces should become more simple and it should be easier to determine if a change in the details effects the abstraction.

To sum up the Dependency Injection Principle is a way to design you classes, so that the have loose coupling and being aware that do not change the abstractions (the implied understanding of what a interface promise to do) of the system. The next blog post will be much more code heavy and will describe how to use Dependency Injection to put the Dependency Injection Principle into use.

Tags:

Dependency Injection | General