Show Menu
Cheatography

Unity Container Cheat Sheet by

Quick Reference for Unity Inversion of Control Container

Essential Links

Example Code

public interface ICar
{
  int Run();
}

public class Car : ICar
{
  private int _miles;

  public int Run()
  {
    return ++_miles;
  }
}	

public class Driver
{
  private ICar _car;

  public Driver(ICar car)
  {
    _car = car;
  }

  public void RunCar()
  {
    Console.WriteLine("Running {0} - {1} mile ", _car.GetType().Name, _car.Run());
  }
}

Register and Resolve

IUnityContainer container = new UnityContainer();
container.RegisterType<ICar, Car>();

//Resolves dependencies and returns the Driver
Driver driver= container.Resolve<Driver>(); 
driver.RunCar();
 

Constr­uctor Injection

[InjectionConstructor]
public Driver(ICar car)
{
    _car = car;
}

Property Injection

[Dependency]
public ICar Car { get; set; }

Register Types

//NuGet Package Unity.RegistrationByConvention
//The interface and class names must match
//ICar and Car
public static void RegisterTypes(IUnityContainer container)
{
  container.RegisterTypes(
    AllClasses.FromLoadedAssemblies(),
    WithMappings.FromMatchingInterface,
    WithName.Default);
}

Register Types In Assembly

RegisterTypesInAssembly(container, 
typeof(Car).Assembly);

public static void RegisterTypesInAssembly 
(IUnityContainer container, Assembly assembly)
{
  IEnumerable<Type> types = assembly.GetTypes()
    .Where(o => o.IsClass
          && !o.IsGenericType
          && !o.IsAbstract
          && o.GetInterfaces().Any());

  foreach (Type type in types)
  {
    container.RegisterType(type.GetInterfaces()
      .First(), type);
  }
}
           
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Oracle SQL Injection Cheat Sheet

          More Cheat Sheets by GregFinzer

          RhinoMocks Cheat Sheet
          AWS Core Service Options Cheat Sheet