Using Unity Injection API
In some previous posts I
explained how to use the
Unity configuration section in
dependency injection scenarios.
In this post I’m going to show
how to use some aspects of the
Unity injection API.
Unity Injection API
When you use Unity sometimes you want to inject dependencies in runtime and
not in configuration files. The use of Unity injection API can help you do it very simple.
In the Unity application block use the Microsoft.Practices.Unity namespace in order
to use the injection API. All the classes that can be used to inject dependencies has
a prefix of Injection and they include the InjectionConstructor, InjectionProperty and etc.
Every injection class inherit the InjectionMember abstract class.
The InjectionMember is the base class for objects that can be used to configure what
class members get injected by the Unity container.
Main Classes of Injection API
There are three injection aspects that are leveraged by the Unity application block.
The three aspects are constructor, properties and methods injection. In the injection
API the classes that represent these aspects are:
- InjectionConstructor - A class that holds the collection of information for a
constructor, so that the Unity container can be configured to call this constructor.
- InjectionProperty - This class stores information about which properties to inject,
and will configure the Unity container accordingly.
- InjectionMethod - An InjectionMember that configures the Unity container to
call a method as part of buildup.
Unity Injection API Example
In the following example I use the SqlDatabase class:
public class SqlDatabase : Database
{
#region Members
private string _connString;
#endregion
#region Properties
public ILogger Logger { get; set; }
public IValidator<int> Validator { get; set; }
#endregion
#region Ctor
public SqlDatabase(string connString)
{
_connString = connString;
}
#endregion
}
All the other classes and interfaces I use can be found in the previous posts I wrote
in the Unity application block series.
The following example shows how to use the injection API:
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, FileLogger>();
container.RegisterType<Database, SqlDatabase>();
container.RegisterType<IValidator<int>, Validator<int>>();
container.Configure<InjectedMembers>().
ConfigureInjectionFor<SqlDatabase>(
new InjectionConstructor(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString),
new InjectionProperty("Logger"),
new InjectionProperty("Validator"));
var database = container.Resolve<Database>();
The container’s Configure method is the main method to use in order to inject members.
It returns an InjectedMembers class which I use it’s ConfigureInjectionFor to inject
aspects for a particular type (in the example the SqlDatabase class).
In the example you can see that I inject the FileLogger into the Logger property,
the Validator<int> into the Validator property and a connection string from
the list of connection strings in the configuration file to the constructor. In the end of the
process the database object will be constructed with the appropriate validator, logger
and connection string all in one instruction of code.
As I wrote earlier the injection API is simple and intuitive.
Summary
To sum up the post, Unity has an injection API that helps to inject dependencies aspects
in runtime. The API is simple to use and I showed an example of how to use it in the post.
I suggest to write some code with the injection API in order to get familiar with it.
Memento Pattern
This post is another post in the design patterns series. The post will describe and
show why and how to use the memento design pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
Builder pattern
Behavioral Patterns
Strategy pattern
Iterator pattern
Template method pattern
Command pattern
Chain of responsibility pattern
Mediator pattern
Memento Pattern
The memento design pattern is a pattern that helps to save the object internal
state in an external place enabling us to restore the state later when needed.
The memento pattern doesn’t violate encapsulation of the internal state.
If you read my previous post about the command pattern you’ll probably remember
the undo example I showed. The example was simple and if you really want to save the
object’s state the memento pattern can help you do that.
Even so, The pattern is rarely used but it’s very helpful in scientific computing or in
computer games (saving of check points in the game for example).
Use Cases for the Memento Pattern
You should use the pattern in the following cases:
- You need to save object’s state and use the saved state later in order to
restore the saved state.
- You don’t want to expose the internal state of your object.
UML Diagram
Example in C#
The following code is an example of how to implement the pattern:
#region Originator
public class Originator<T>
{
#region Properties
public T State { get; set; }
#endregion
#region Methods
/// <summary>
/// Creates a new memento to hold the current
/// state
/// </summary>
/// <returns>The created memento</returns>
public Memento<T> SaveMemento()
{
return (new Memento<T>(State));
}
/// <summary>
/// Restores the state which is saved in the given memento
/// </summary>
/// <param name="memento">The given memento</param>
public void RestoreMemento(Memento<T> memento)
{
State = memento.State;
}
#endregion
}
#endregion
#region Memento
public class Memento<T>
{
#region Properties
public T State { get; private set; }
#endregion
#region Ctor
/// <summary>
/// Construct a new memento object with the
/// given state
/// </summary>
/// <param name="state">The given state</param>
public Memento(T state)
{
State = state;
}
#endregion
}
#endregion
#region Caretaker
public class Caretaker<T>
{
#region Properties
public Memento<T> Memento { get; set; }
#endregion
}
#endregion
The given example shows the three parts of the pattern: the Originator, the Memento
and the Caretaker. The Caretaker is the repository for the Memento. You can also see
that once the Memento object is created you can’t change the saved state and in order
to save a new Memento you need to create it again.
Lets look at an example of how to use the pattern in code:
Originator<string> org = new Originator<string>();
org.State = "Old State";
// Store internal state in the caretaker object
Caretaker<string> caretaker = new Caretaker<string>();
caretaker.Memento = org.SaveMemento();
Console.WriteLine("This is the old state: {0}", org.State);
org.State = "New state";
Console.WriteLine("This is the new state: {0}", org.State);
// Restore saved state from the caretaker
org.RestoreMemento(caretaker.Memento);
Console.WriteLine("Old state was restored: {0}", org.State);
// Wait for user
Console.Read();
As you can see the saved state is inserted to the Caretaker object and than
you can change the state of the Originator to whatever you need. In order to
restore the Originator state you use the restore method and pass it the Caretaker’s
saved Memento.
Summary
To sum up the post, the memento pattern is is used for saving encapsulated object state
in an external object. The state can then be restored by demand.
As I wrote the places that you’ll want to use the pattern are in scientific
computing or in computer games but it can be helpful also in other places.
The next post in the series will explain the state pattern.