Archive

Posts Tagged ‘Dependency Injection’

Dependency Injection in ASP.NET MVC3

February 11, 2011 2 comments

What dependency injection means is that instead of writing code like this in your controller

private IBlogService _BlogService;
public BlogController()
{
    _BlogService = new BlogService();
}

you write code like this

private IBlogService _BlogService;
public BlogController(IBlogService blogService)
{
    _BlogService = blogService;
}

the benefits of dependency injection are your classes are not tightly coupled, are more testable, and really is pluggable.

To enable dependency injection into your controllers in ASP.NET MVC2 you had to create a new class derived from DefaultControllerFactory and override the GetControllerInstance method to create the controller using your dependency injection container e.g.

public class IoCControllerFactory : DefaultControllerFactory
{

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (IController)_container.GetInstance(controllerType);
    }
}

and then you had to register this controller factory as the default in the Application_Start event in the global.ascx file

protected void Application_Start()
{

    ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));
    ...
}

The problem here is that you need to create a separate custom class for the model binders, and for custom model metadata.

ASP.NET MVC 3 makes things easier to inject dependencies by introducing a new interface IDependencyResolver. The benefit here is that this DependencyResolver is responsible to resolve dependencies not only for the controller but also for the services (repository, logger etc.) consumed by the controller, view engine, view binders, and the model and model metadata.

The interface has two methods

object GetService(Type serviceType);
IEnumerable<object> GetServices(Type serviceType);

which return either a single object or a list of object of serviceType. If a type cannot be resolved by the dependency resolver then ASP.NET MVC3 expects the resolver to return null.

If the dependency resolver returns null then ASP.NET MVC3 will fall back to the default factory class to instantiate the interface object.

To use this new interface simply create a new class which implements this interface

public class UnityDependencyResolver : IDependencyResolver
{
    private IUnityContainer _contianer;
    UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    #region IDependencyResolver Members
    public object GetService(Type serviceType)
    {
        try
        {
            return _container.GetInstance(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.GetAllInstances(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    #endregion
}

I’m using Unity as my dependency container and since Unity throws a ResolutionFailedException exception if it cannot resolve a  type we need to wrap it in a try/catch block and return null in case of exception.

Just like the controller factory we need to register our dependency resolver at Application_Start event in our global.ascx

protected void Application_Start()
{
    var container = new UnityContainer()
        .LoadConfiguration();

    DependencyResolver.SetResolver(container);
    ...
}

You can either configure your container at runtime or via the .config file. I prefer the .config approach because then I can easily take my application to any environment (DEv vs QA) and switch out my EmailLogger with NullLogger or as required by changing the mapping in the .config file.

Unity – Dependency Injection and Inversion of Control Container

September 8, 2008 10 comments

The Dependency Injection Pattern
Dependency injection is a programming technique to reduce component coupling. Dependency injection is also commonly known as “inversion of control” or IoC or sometimes as The Hollywood Principle – "Don’t call us, we’ll call you”. The goal of dependency injection is to separate the concerns of how a dependency is obtained from the core concerns of a boundary. This improves reusability by enabling components to be supplied with dependencies which may vary depending on context.

The Old Way
Following is an example of how you might write code if not using dependency injection

public class WebApp { public WebApp() { quotes = new StockQuotes(); authenticator = new Authenticator(); database = new Database(); logger = new Logger(); errorHandler = new ErrorHandler(); } }

Problem

  • What about the child objects?
  • How does the StockQuotes find the Logger?
  • How does the Authenticator find the database?
  • Suppose you want to use a TestingLogger instead? Or a MockDatabase?

Service Locator pattern attempts to solve some of the problems mentioned above by providing a dictionary of objects. The objects are all stored in this dictionary and the Get method simply returns the object to the caller.

Service Locator Example

public interface ILocator { TObject Get<TObject>(); } public class MyLocator : ILocator { protected Dictionary<Type, object> dict = new Dictionary<Type,object>(); public MyLocator() { dict.Add(typeof(ILogger), new Logger()); dict.Add(typeof(IErrorHandler), new ErrorHandler(this)); dict.Add(typeof(IQuotes), new StockQuotes(this)); dict.Add(typeof(IDatabase), new Database(this)); dict.Add(typeof(IAuthenticator), new Authenticator(this)); dict.Add(typeof(WebApp), new WebApp(this)); } } public class StockQuotes { public StockQuotes(ILocator locator) { errorHandler = locator.Get<IErrorHandler>(); logger = locator.Get<ILogger>(); } }

Pros

  • Classes are decoupled from explicit implementation types
  • Easy to externalize the config

Cons

  • Everyone takes a dependency on the ILocator
  • Hard to store constants and other useful primitives
  • Creation order is still a problem

Dependency Injection Containers
The dependency injection container is a component responsible for assigning dependencies to a recipient component. Containers are generally implemented using the Factory Pattern to allow creation of the recipient and dependency components. Containers are often implemented to allow existing objects to be registered for use as a dependency, or to create new instances when required. Using a dependency injection container with our StockQuotes example provides the following benefits:

  • Gets rid of the dependency on the ILocator
  • Object is no longer responsible for finding its dependencies
  • The container does it for you

In a nutshell, dependency injection just means that a given class or system is no longer responsible for instantiating their own dependencies. In this case “Inversion of Control” refers to moving the responsibility for locating and attaching dependency objects to another class or a DI tool. That might not sound that terribly profound, but it opens the door for a lot of interesting scenarios.
Benefits of Dependency Injection:

  • Dependency Injection is an important pattern for creating classes that are easier to unit test in isolation
  • Promotes loose coupling between classes and subsystems
  • Adds potential flexibility to a codebase for future changes
  • Can enable better code reuse

Unity Application Block
Unity Application Block is a lightweight Inversion of Control container which supports constructor, property and method call injection. Unity sits on top of another framework called ObjectBuilder, but is different from the ObjectBuilder which has been a part of Enterprise Library 3.1 and earlier. Unity is based on v2 of the Objectbuilder and has been optimized for performance quite a bit. Unity is available both as a standalone and part of Enterprise Library 4.0 on codeplex at http://www.codeplex.com/unity and http://www.codeplex.com/entlib. Unity 1.1 is not part of Enterprise Library 4.0 but the good thing about it is that it will update the Unity dlls/libraries in Enterprise Library 4.0 installed folder to 1.1 during installation.

The Unity Application Block includes the following features:

  • It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.
  • It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.
  • It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection), or apply attributes to properties and methods to initiate property injection and method call injection.
  • It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).
  • It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container.
  • It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.
  • It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching.

Unity has no dependency on Enterprise Library core and can be used without having to install Enterprise Library on the host system. To use Unity in your application you need to add reference to the following dlls in your project
    Microsoft.Practices.ObjectBuilder2
    Microsoft.Practices.Unity

The Unity container can be configured through configuration files or you can use code to register dependencies dynamically at run time. To use Unity with configuration files you need to add reference to the following dll
    Microsoft.Practices.Unity.Configuration

Steps when using Dependency Injection

  • Write your objects the way you want
  • Setup the container
  • Ask the container for objects
  • The container creates objects for you and fulfills dependencies

Setup the container
The ideal place to setup the Unity container for ASP.NET applications is in the Application_Start method of the global.asax file. We would like to have a persistent container that hold it’s state during the execution of the application. The right place to put this is in the Global.asax file as a property of the current application.

We create a simple interface for the container property so that we can access our container using this interface

public interface IContainerAccessor { IUnityContainer Container { get; } }

class in the Global.asax file:

private static UnityContainer _container; public static UnityContainer Container { get { return _container; } set { _container = value; } } protected void Application_Start(object sender, EventArgs e) { BuildContainer(); } protected void Application_End(object sender, EventArgs e) { CleanUp(); } private static void BuildContainer() { IUnityContainer container = new UnityContainer(); //TODO: Register the relevant types for the container here through classes or configuration Container = container; } private static void CleanUp() { if (Container != null) { Container.Dispose(); } }

The BuildContainer method is where we will setup our container and register our types for dependency injection. The RegisterType<TFrom, TTo>() method tells Unity that whenever someone asks for a dependency on TFrom give them Tto. In the example code below the statement container.RegisterType<ILogger, EventLogLogger>() tells Unity that whenever someone has a dependency on type ILogger go ahead and create an object of type EventLogLogger.

There are a couple of different flavors of Dependency Injection

  • Constructor Injection – Attach the dependencies through a constructor function at object creation
  • Setter Injection – Attach the dependencies through setter properties
  • Service Locator – Use a well known class that knows how to retrieve and create dependencies. Not technically DI, but this is what most DI/IoC container tools really do

Constructor Injection

public interface ILogger { void LogEvent(string message); } public class FileLogger : ILogger { public void LogEvent(string message) { ... } } public class EventLogLogger : ILogger { public void LogEvent(string message) { ... } } public class StockQuotes { private Ilogger _logger; public class StockQuotes(ILogger logger) { _logger = logger; } } UnityContainer container = new UnityContainer(); ... contianer.RegisterType<ILogger, EventLogLogger>(); StockQuotes quotes = container.Resolve<StockQuotes>();

If a class that developers instantiate using the Resolve method of the Unity container has a constructor that defines one or more dependencies on other classes, the Unity container will automatically create the dependent object instance specified in parameters of the constructor. In the above example StockQuotes has a dependency on ILogger. When we create an instance of the StockQuotes class using the Resolve method of the Unity container, Unity will automatically create an instance of EventLogLogger and pass it to the constructor of StockQuotes class.

The benefit of using constructor injection is that the constructor function now explicitly declares the dependencies of a class. Constructor injection is often recommended as it eliminates chatty calls to the object and creates a valid object in as few steps as possible.

Setter Injection

public class OracleDatabase : IDatabase { Public void ExecuteQuery(string query) { ... } } public class SqlDatabase : IDatabase { public void ExecuteQuery(string query) { ... } } public class Authenticator { private IDatabase _database; [Dependency] public IDatabase DB { get{return _database;} set{_database = value;} } } UnityContainer container = new UnityContainer(); ... contianer.RegisterType<IDatabase, SqlDatabase>(); Authenticator auth = container.Resolve<Authenticator>();

To force dependency injection of the dependent object, developers must apply the [Dependency] attribute to the property declaration. Many would argue that setter injection is really useful when legacy code needs to be upgraded and provides a smooth transition from legacy code to the new model. Making sure that any new code that depends on undesirable legacy code uses Dependency Injection leaves an easier migration path to eliminate the legacy code later with all new code. 

As a service locator

UnityContainer container = new UnityContainer(); contianer.RegisterType<ILogger, NullLogger>(); … ILogger logger = container.Resolve<ILogger>();

Here we are just telling unity to give us the ILogger interface which is already registered with the container. Using the container in this manner makes it a service locator.

Unity Dependency injection provides a number of ways to configure the container. As described above you use the RegisterType method to inform the container about dependencies. But Unity can also manage the object lifetime e.g.

Dependencies as singleton

UnityContainer container = new UnityContainer(); container.RegisterType<Database, SqlDatabase>(new ContainerControlledLifetimeManager());

The above code  tells Unity that whenever someone asks for type Database give them type SqlDatabase and return the same object every time instead of creating a new one for each dependency.

Named Instance

UnityContainer container = new UnityContainer(); contianer.RegisterType<Database, SqlDatabase>("SQL"); container.RegisterType<Database, OracleDatabase>("Oracle"); IEnumerable<Database> databases = container.ResolveAll<Database>(); Database database = container.Resolve<Database>("SQL");

Named instance allows you to configure Unity with multiple dependencies for the same type but assign them different names. Thi s allows you to do fancy stuff where you want a default type mapping but also want to override the mapping by providing a name during object creation.

Registering an existing object instance
So far all the examples above show how a type can be registered with Unity and the Unity container creates the object for you whenever requested. But what if you already have the object created and want to register this object in Unity.

UnityContainer container = new UnityContainer(); contianer,RegisterInstance<Database>(new SqlDatabase()); contianer.RegisterInstance<Database>("Oracle", new OracleDatabase()); Database database = container.Resolve<Database>(); Database oracleDatabase = container.Resolve<Database>("Oracle");

When using RegisterIntance Unity will automatically make the objects singletons.

Configuring Unity via config file
The Unity container can be configured through configuration files. To use Unity with configuration files you need to add reference to the following dll
    Microsoft.Practices.Unity.Configuration

Use following code to read the container setup from configuration file:

UnityContainer container = new UnityContainer(); UnityConfgurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); Section.Containers.Default.GetConfigCommand().Configure(); ILogger logger = container.Resolve<ILogger>();

.config file:

<configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <typeAliases> <!-- Lifetime manager types --> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /> <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,Microsoft.Practices.Unity" /> </typeAliases> <containers> <container> <types> <type type="ConsoleApplication1.Database, ConsoleApplication1" mapTo="ConsoleApplication1.SqlDatabase, ConsoleApplication1" lifetime="Singleton" /> <type type="ConsoleApplication1.ILogger, ConsoleApplication1" mapTo="ConsoleApplication1.EvnetLogLogger, ConsoleApplication1" lifetime="Singleton" /> </types> </container> </containers> </unity>

Nested Containers
Unity supports nested containers, which allows the parent container to create child containers. This provides the ability to override parent type mappings with child type mappings. Parent-Child relationship between Unity containers. What this means is that the parent-child relationship between Unity containers will search the child container to the resolve the type mapping, and if not found, will navigate up to the parent container to resolve the type.

UnityContainer parentContainer = new UnityContainer(); IUnityContainer childContainer1 = parentContainer.CreateChildContainer(); IUnityContainer childContainer2 = parentContainer.CreateChildContainer(); parentContainer.RegisterType<ILogger, FileLogger>(new ContainerControlledLifetimeManager()); childContainer1.RegisterType<ILogger, EventLogLogger>(new ContainerControlledLifetimeManager()); ILogger logger = childContainer2.Resolve<ILogger>(); // should return FileLogger from parentContainer ILogger logger2 = childContainer1.Resolve<ILogger>(); //should return EventLogLogger from childContainer1

While registering types with Unity there is a certain risk of introducing unintentional circular references, which are not easy to detect or prevent.
For example, the following code shows two classes that reference each other in their constructors.

public class Class1 { public Class1(Class2 test2) { ... } } public class Class2 { public Class2(Class1 test1) { ... } }

It is the responsibility of the developer to prevent this type of error by ensuring that the members of classes they use with dependency injection do not contain circular references.

References

Dependency Injection: Factory vs Container – Unity

June 30, 2008 Leave a comment

As application size and complexity increase it becomes more and more difficult to reuse existing components and integrating these components to form an interconnected architecture because of the dependencies of the components. One way to reduce dependencies is by using Dependency Injection, which allows you to inject objects into a class, rather than relying on the class to create the object itself.

Dependency Injection refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency. The basic value Dependency Injection brings to enterprise systems is decoupling. They promote programming to interfaces and isolate you from the creation process of the collaborators, letting you to concentrate on what you need to deliver while improving testing.

The dependency injection approach offers more flexibility because it becomes easier to create alternative implementations of a given service type, and then to specify which implementation is to be used either pragmatically or via a configuration file, without any change to the objects that use the service. This is especially useful in unit testing, because it is easy to inject a mock implementation of a service into the object being tested.

Dependency injection helps in solving the following

  • You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes source code.
  • You want to be able to write classes that depend on classes whose concrete implementation is not known at compile time.
  • You want to be able to test your classes in isolation, without using the dependencies.
  • You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.

    The factory pattern described as "To construct and instantiate a set of related objects without specifying their concrete objects." is one common way to implement Dependency Injection. When a component creates an instance of another class, it encapsulates the object creation logic within the component. Any other class that requires an instance of the created class must also duplicate the object creation logic as it may not be reusable outside the component.

    Object most often need to be instantiated in a coordinated fashion, usually because of certain dependencies or other requirements. For example, when creating an instance of XmlValidatingReader in client code, an XmlSchemaCollection object is frequently populated with the relevant schemas for use when validating the XmlValidatingReader object. This is an example of needing to not only create an instance of a class, but also to configure it after creation and before it can be used.

    Another example of a factory pattern is to create a static method whose purpose is to return an instance of a class. For example, the Create method of WebRequest takes in either a string or Uri instance, and returns a new instance of a class derived from WebRequest.

    Factories allow for an application to wire together objects and components without exposing too much information about how the components fit together or what dependencies each component might have. Instead of spreading complex creating code around an application, factories allow for that code to be housed in a central location, thereby facilitating reuse throughout the application.

    Client code then calls creating methods on the factory, with the factory returning complete instances of the requested classes. Encapsulation is preserved, and the client is effectively decoupled from any sort of plumbing required to create or configure the object instance.

    Benefits of Factory Pattern

  • Factories allow for an application to wire together objects and components without exposing too much information about how the components fit together or what dependencies each component might have.
  • Instead of spreading complex creating code around an application, factories allow for that code to be housed in a central location, thereby facilitating reuse throughout the application.
  • Client code calls creating methods on the factory, with the factory returning complete instances of the requested classes. Encapsulation is preserved, and the client is effectively decoupled from any sort of plumbing required to create or configure the object instance.

    Drawbacks of factory pattern

  • While a factory implementation can be quite valuable for a certain application, most of the time, it is not reusable across other applications. Frequently all of the available creation options are hardcoded into the factory implementation, making the factory itself non-extensible. Most of the time the class calling the factories’ creation methods must know which subclass of the factory to create.
  • All dependencies for an object that is created using a factory are known to the factory at compile time. At run time there is no way to insert or alter the manner in which objects are created, or which dependencies are populated. This all must happen at design time, or at least require a recompile. For example, if a factory is creating instances of class Foo and instances of class Foo require an instance of class Bar, then the factory must know how to retrieve an instance of the Bar class. The factory could create a new instance, or even make a call to another factory.
  • Since factories are custom to each individual implementation, there can be a significant level of cross-cutting infrastructure that is held captive inside a particular factory. Take my example of a factory dynamically substituting a proxy object for a real object. That is an example of a piece of infrastructure, namely the wrapping of simple objects for deployment over a distributed wire, that is completely encapsulated inside that particular factory. If another object needs to be altered in a similar manner, the logic to do so is hidden inside a factory, and would have to be repeated for the other object. Once this functionality is desired outside of the original application, the problem now becomes how to reuse such functionality while still maintaining the existing factory concept.
  • Factories rely on well-defined interfaces to achieve polymorphism. In order for a factory implementation to be able to dynamically create different concrete subclass instances, there must be a common base class or shared interface implemented by all classes that the factory will create. Interfaces decouple the construction of the object from the specific implementation of the interface. The dilemma that arises now is how you can accomplish this decoupling without being forced to create an interface for everything.

    A container is a compartment that houses some sort of abstraction within its walls. Typically, responsibility for object management is taken over by whatever container is being used to manage those objects. However, containers can also take over instantiations, configuration, as well as the application of container-specific services to objects.

    Containers provide the ability to wrap vanilla objects with a wealth of other services. This allows the objects to remain ignorant about certain infrastructure and plumbing details, like transactionality and role-based security. Oftentimes, the client code does not need to be aware of the container, so there is no real dependency on the container itself. Containers be configured declaratively, meaning they can be configured via some external means, XML files, property files, or .NET-based attributes.

    Dependency Injection is a worthwhile concept to explore for use within applications that you develop. Not only can it reduce coupling between components, but it also saves you from writing boilerplate factory creation code over and over again. Unity is an example of a framework that provides a ready to use Dependency Injection container. Of course all this also means that there is added complexity to the source code; therefore, it is harder to understand.

    Microsoft Patterns and Practices team had been developing Enterprise Library to enable the use of general patterns and practices for .NET platform, which has great pluggable application blocks such as Logging and Validation application blocks. One of them is the Dependency Injection Application Block; but folks thought it should be named differently from the other application blocks, and came with the fancy name Unity.

    Unity exposes Register methods that support configuring the container with mappings and objects (including singleton instances), and Resolve methods to return instances of built objects that contain any dependent objects. Unity sits on top of another framework called ObjectBuilder which has been a part of enterprise library for quite some time. Unity however is based on v2.0 of the object builder which has been tweaked, refactored and optimized for performance. Unity is available as both a standalone download or part of the enterprise library and can be downloaded from http://www.codeplex.com/unity or http://www.codeplex.com/entlib.

    Unity supports the following forms of dependency injection:

  • Constructor injection – parameters of the objects constructor method are used to inject it with its dependencies.
  • Setter injection – object simply provides a property that can hold a reference to that type of service; and when the object is created a reference to an implementation of that type of service will automatically be injected into that property – by an external mechanism.

    David Hayden has done some great screencasts on Enterprise Library and Unity at http://www.pnpguidance.net/ be sure the check them out for furhter readings on dependency injection using Unity Applicaiton Block.

    Technorati Tags: ,