var c = new UnityContainer();

Example 1:

// Register ZLogger as an implementor of ILogger
c.RegisterType<ILogger, ZLogger>();
// Create a new instance of ZLogger.
var logger = c.Resolve<ILogger>();

Example 2:

// Register ZLogger as an implementor of ILogger.  Resolve will return a singleton (container controlled lifetime)
c.RegisterType<ILogger, ZLogger>( new ContainerControlledLifetimeManager());
// Get the singleton instance of ZLogger (creating it the first time)
var logger = c.Resolve<ILogger>();

Example 3:

// Regsiter an existing instance of an ILogger implementation.  Resolve will always return this instance.
// Get the single registered instance of ILogger.
var logger = c.Resolve<ILogger>();

Example 4:

// What if ZLogger's constructor requires that the caller pass in an instance of ZStorage class.
// This is solved by registering ZStorage type into the container.
// The rest of the code is the same as Example 1:
c.RegisterType<ILogger, ZLogger>();
var logger = c.Resolve<ILogger>();

Example 5:

// What if ZLogger had a public property caller LogFlags which can be set by a client.
// We can decorate the property in the logger class with the attribute [Dependency]
public LogFlagManager LogFlags
   get { return _logFlags; }
   set { _logFlags = value; }
Now, creating an instance of the ZLogger class automatically generates an instance of the LogFlagManager class and sets it as the value of the LogFlags property of the ZLogger class.

// Example of configuring from the container from a configuration file.
//These examples use the App.Config/Web.Config file.

// Example code reading the defaul container from the config file
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

// To read from a specific container, change the last line to:

// To create a hierarchy of nested containers
var pc = new UnityContainer();
var cc = parentContainer.CreateChildContainer();

var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");


// Using an external XML configuration file:
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "MyConfig.config";
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

        <section name="unity"
         type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,                Microsoft.Practices.Unity.Configuration"/>
// Example of creating some aliases.  This go into the <unity></unity> section
            <!-- Lifetime manager types -->
            <typeAlias alias="singleton"
                      Microsoft.Practices.Unity" />
            <typeAlias alias="perThread"
                      Microsoft.Practices.Unity" />
            <typeAlias alias="external"
                      Microsoft.Practices.Unity" />

            <!-- User-defined type aliases -->
            <typeAlias alias="IMyInterface"
                     type="MyApplication.MyTypes.MyInterface, MyApplication.MyTypes" />
            <typeAlias alias="MyRealObject"
                     type="MyApplication.MyTypes.MyRealObject, MyApplication.MyTypes" />
            <typeAlias alias="IMyService"
                     type="MyApplication.MyTypes.MyService, MyApplication.MyTypes" />
            <typeAlias alias="MyDataService"
                     type="MyApplication.MyTypes.MyDataService, MyApplication.MyTypes" />
            <typeAlias alias="MyCustomLifetime"
                     type="MyApplication.MyLifetimeManager, MyApplication.MyTypes" />
// Example of creating some containers.  These usually go after the <typeAliases></typeAliases> sectin

          <container name="containerOne">

              <!-- Type mapping with no lifetime – defaults to "transient" -->
              <type type="Custom.MyBaseClass" mapTo="Custom.MyConcreteClass" />

              <!-- Type mapping using aliasesdefined above -->
              <type type="IMyInterface" mapTo="MyRealObject" name="MyMapping" />

              <!-- Lifetime managers specified using the type aliases -->
              <type type="Custom.MyBaseClass" mapTo="Custom.MyConcreteClass">
                <lifetime type="singleton" />

              <type type="IMyInterface" mapTo="MyRealObject" name="RealObject">
                <lifetime type="perThread" />

              <type type="IMyInterface" mapTo="MyRealObject" name="RealObject">
                <lifetime type="external" />

              <!-- Lifetime manager specified using the full type name -->
              <!-- Any initialization data specified for the lifetime manager -->
              <!-- will be converted using the default type converter -->
              <type type="Custom.MyBaseClass" mapTo="Custom.MyConcreteClass">
                <lifetime value="sessionKey" type="MyApplication.MyTypes.MyLifetimeManager, MyApplication.MyTypes" />

              <!-- Lifetime manager initialization using a custom TypeConverter -->
              <type type="IMyInterface" mapTo="MyRealObject" name="CustomSession">
                <lifetime type="MyCustomLifetime" value="ReverseKey" typeConverter="MyApplication.MyTypes.MyTypeConverter, MyApplication.MyTypes" />

              <!-- Object with injection parameters defined in configuration -->
              <!-- Type mapping using aliases defined above -->
              <type type="IMyService" mapTo="MyDataService" name="DataService">
                <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
                    <param name="connectionString" parameterType="string">
                      <value value="AdventureWorks"/>
                    <param name="logger" parameterType="ILogger">
                      <dependency />

                  <property name="Logger" propertyType="ILogger" />

                  <method name="Initialize">
                    <param name="connectionString" parameterType="string">
                      <value value="contoso"/>
                    <param name="dataService" parameterType="IMyService">
                      <dependency />

              <add name="MyInstance1" type="System.String" value="Some value" />
              <add name="MyInstance2" type="System.DateTime" value="2008-02-05T17:50:00" />

              <add type="MyApp.MyExtensions.SpecialOne" />

              <add name="MyExtensionConfigHandler" type="MyApp.MyExtensions.SpecialOne.ConfigHandler" />

          <!-- ... more containers here ... -->


RegisterType<TInterface, TType>();





container.RegisterType<ILogger, NullLogger>();
Database database = container.Resolve<CustomDatabase>();

;CustomDatabase class constructor requires ILogger.  CustomDatabase doesn't have to be registered with the container

ILogger logger = Container.Resolve<ILogger>();

;Resolve creates a new ILogger each time, unless you want a singleton.

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

container.RegisterType<Database, SQLDatabase>( "SQL" );
container.RegisterType<Database, OracleDatabase>( "ORACLE" );

Database database = container.Resolve<Database>("SQL");
;using aliases.

IEnumerable<Database> databases = container.ResolveAll<Database>();
; return two databases, one for SQL one for ORACLE

container.RegisterInstance<Database>( new SqlDatabase() );
container.RegisterInstance<Database>( "Oracle", new OracleDatabase() );
; automatically a singleton.

Database database = container.Resolve<Database>();
; returns the SqlDatabase instance -- the default.

container.RegisterType<ILogger, NullLogger>();

DB2Database existingDatabase = new DB2Database();


Database database = container.Resolve<Databsae>();

;DB2Database has a public property [Dependency] on ILogger.
;BuildUp injects the dependencies

UnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
ICustomerDatabase datasource = container.Resolve<ICustomerDataSource>();

IUnityContainer = childContainer = parentContainer.CreateChildContainer();
parentContainer.RegisterType<ILogger, NullLogger>( new ContainerControlledLifetimeManager());
ILogger logger = childContainer.Resolve<ILogger>();
;childContainer doesn't have ILogger, so it goes to the parent.

;VirtualMethodInterceptor example

IUnityContainer container = new UnityContainer();
SetInterceptorFor<Logger>(new VirtualMethodInterceptor());
var logger = container.Resolve<Logger>();

public class Logger {
  public virtual void Write(string message) {
} }

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.