FANDOM


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.
c.RegisterInstance<ILogger>(existingLogger);
// 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.
c.RegisterType<ZStorage>();
// 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]
[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");
section.Containers.Default.Configure(c);

// To read from a specific container, change the last line to:
section.Containers["containerOne"].Configure(c);

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

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

section.Containers["containerOne"].GetConfigCommand().Configure(pc);
section.Containers["nestedChildContainer"].Configure(pc);

// 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.Containers["containerOne"].Configure(c);


//Example:
<configuration>
    <configSections>
        <section name="unity"
         type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,                Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <unity>
        ...
        ...
    </unity>
    ...
    ...
</configuration>
// Example of creating some aliases.  This go into the <unity></unity> section
        <typeAliases>
            <!-- Lifetime manager types -->
            <typeAlias alias="singleton"
                      type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
                      Microsoft.Practices.Unity" />
            <typeAlias alias="perThread"
                      type="Microsoft.Practices.Unity.PerThreadLifetimeManager,
                      Microsoft.Practices.Unity" />
            <typeAlias alias="external"
                      type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
                      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" />
        </typeAliases>
// Example of creating some containers.  These usually go after the <typeAliases></typeAliases> sectin

        <containers>
          <container name="containerOne">
            <types>

              <!-- 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 type="IMyInterface" mapTo="MyRealObject" name="RealObject">
                <lifetime type="perThread" />
              </type>

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


              <!-- 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" />
              </type>

              <!-- 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" />
              </type>

              <!-- 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">
                  <constructor>
                    <param name="connectionString" parameterType="string">
                      <value value="AdventureWorks"/>
                    </param>
                    <param name="logger" parameterType="ILogger">
                      <dependency />
                    </param>
                  </constructor>

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

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

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

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

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

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

        </containers>




RegisterType<TInterface, TType>();

RegisterInstance<Tinterface>(exitingObject);

Resolve<TInterface>();

Resolve<TType>();

BuildUp<TTtype>(existingObject)


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();
container.BuildUp(existingDatabase)

container.RegisterInstance<Database>(existingDatabase)

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");
section.Containers.Default.GetConfigCommand().Configure(container)
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();
container.AddNewExtension<Interception>();
container.RegisterType<Logger>();
container.Configure<Interception>().
SetInterceptorFor<Logger>(new VirtualMethodInterceptor());
var logger = container.Resolve<Logger>();
logger.Write("World.");

public class Logger {
  public virtual void Write(string message) {
    Console.Write(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.