Show / Hide Table of Contents

Interface IUnityContainer

Interface defining the behavior of the Unity dependency injection container.

This interface defines a compact API that allows registration of types, instances, and factories, resolution of new objects or initialization of existing instances, scope manipulations, and etc.

Inherited Members
IDisposable.Dispose()
Namespace: Unity
Assembly: Unity.Abstractions.dll
Syntax
[CLSCompliant(true)]
public interface IUnityContainer : IDisposable

Properties

| Improve this Doc View Source

Parent

The parent of this container.

Declaration
IUnityContainer Parent { get; }
Property Value
Type Description
IUnityContainer

The parent container, or null if this container doesn't have one.

Remarks

If the instance of the container is a child container, this property will hold a reference to the container that created this instance.

| Improve this Doc View Source

Registrations

Lists all registrations available at this container.

Declaration
IEnumerable<IContainerRegistration> Registrations { get; }
Property Value
Type Description
IEnumerable<IContainerRegistration>

Registered with the container types

Remarks

This collection contains all registrations from this container.

If this is a child container Registrations will contain all registrations from this container as well as registrations from all predecessor containers. Registrations in child containers override registrations of the same type and name from parent containers.

The sort order of returned registrations is not guaranteed in any way.

See Also
IContainerRegistration

Methods

| Improve this Doc View Source

BuildUp(Type, Object, String, ResolverOverride[])

Run an existing object through the build pipeline and perform injections on it

Declaration
object BuildUp(Type type, object existing, string name, params ResolverOverride[] overrides)
Parameters
Type Name Description
Type type

Type of object to perform injection on.

Object existing

Instance to the object.

String name

name to use when looking up the registration and other configurations.

ResolverOverride[] overrides

Any overrides for the resolve calls.

Returns
Type Description
Object

The resulting object. By default, this will be existing, but container extensions may add things like automatic proxy creation which would cause this to return a different object (but still type compatible with type).

Remarks

This method performs all the initializations and injections on an instance of an object you passed in existing.

This method is useful when you don't control the construction of an instance (ASP.NET pages or objects created via XAML, for instance) but you still want properties and other injections performed.

Exceptions
Type Condition
ResolutionFailedException

Throws if any errors occur during initialization

See Also
Override
| Improve this Doc View Source

CreateChildContainer()

Create a child container.

Declaration
IUnityContainer CreateChildContainer()
Returns
Type Description
IUnityContainer

The new child container.

Remarks

Unity allows creating scopes with the help of child container. A child container shares the parent's configuration but can be configured with different settings or lifetime.

| Improve this Doc View Source

IsRegistered(Type, String)

Checks if Type is registered with container

Declaration
bool IsRegistered(Type type, string name)
Parameters
Type Name Description
Type type

Type to look for

String name

Name of the registration

Returns
Type Description
Boolean

True if Type is registered or False if no registration found

Remarks

This method checks if Type with the specified name is registered with the container.

When method verifies if Type is registered, it looks not only into the current container by all its predecessors as well. So if this Type not registered in the container but contained by one of its parents it will still return True.

This method is quite fast. It uses the same algorithm the container employs to obtain registrations and has a very small overhead. It is an order of magnitude faster than querying Registrations collection.

| Improve this Doc View Source

RegisterFactory(Type, String, Func<IUnityContainer, Type, String, Object>, IFactoryLifetimeManager)

Register Type factory with the container

Declaration
IUnityContainer RegisterFactory(Type type, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager)
Parameters
Type Name Description
Type type

Registration Type. A Type the factory will create when requested

String name

Registration name

Func<IUnityContainer, Type, String, Object> factory

Predefined factory delegate

IFactoryLifetimeManager lifetimeManager

The FactoryLifetime that controls the lifetime of objects. If lifetimeManager is null, container uses default Transient lifetime

Returns
Type Description
IUnityContainer

The IUnityContainer object that this method was called on.

Remarks

This method allows registration of factory function for specific Type.

This registration is very similar to RegisterType(Type, Type, String, ITypeLifetimeManager, InjectionMember[]) except when registered Type is requested, instead of creating the Type, the container invokes registered factory delegate and returns the instance the delegate created.

Examples

This example registers a service factory with transient lifetime.

c.RegisterInstance(typeof(IService),           // Type to register
                   "Some Service",             // Registration name
                   (c,t,n) => new Service(),   // Factory
                   null);                      // Transient
Exceptions
Type Condition
InvalidOperationException

If delegate is null method throws

See Also
FactoryLifetime
| Improve this Doc View Source

RegisterInstance(Type, String, Object, IInstanceLifetimeManager)

Register an instance with the container.

Declaration
IUnityContainer RegisterInstance(Type type, string name, object instance, IInstanceLifetimeManager lifetimeManager)
Parameters
Type Name Description
Type type

Registration Type. This parameter could be either null or any of the interface types the instance implements. If type is null the instance will be registered by its Type

String name

Registration name

Object instance

The Object to be registered

IInstanceLifetimeManager lifetimeManager

An InstanceLifetime manager that controls the lifetime. If no manager is provided (lifetimeManager == null) container uses PerContainer lifetime by default

Returns
Type Description
IUnityContainer

The IUnityContainer object that this method was called on.

Remarks

Instance registration makes objects created outside of the container to be available for dependency injection. Container registers the instance as either Type provided in type, or as Type of the object itself (instance.GetType()).

Instances created outside of container are treated as various types of singletons. There are three different lifetimes an instance supports:

  • External- Instance is managed elsewhere. The container holds just a weak reference to the instance. An author is responsible for making sure the instance is not going out of scope and garbage collected while still being used by the container.
  • Singleton- The instance is registered as a global singleton. This type of lifetime registers the instance with the root container and makes it available to all descendants. It does not matter if an instance is registered with root container or any child containers, the registration is always stored at the root.
  • PerContainer- Instance is registered with a particular container and is available within the container and all its descendants.

Examples

This example registers a default (no name) service instance with externally controlled lifetime.

c.RegisterInstance(typeof(IService),           // Type to register
                   null,                       // Default (no name)
                   instance,                   // Instance of Service
                   InstanceLifetime.External); // Externally controlled
Exceptions
Type Condition
InvalidOperationException

If types of registration and the instance are not assignable, method throws an exception

See Also
InstanceLifetime
| Improve this Doc View Source

RegisterType(Type, Type, String, ITypeLifetimeManager, InjectionMember[])

Register a type or a type mapping with the container.

Declaration
IUnityContainer RegisterType(Type registeredType, Type mappedToType, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
Parameters
Type Name Description
Type registeredType

Registration Type. This Type will be requested when resolving. Sometimes referred as FromType or ServiceType

Type mappedToType

A Type that will actually be returned. Also referred as ToType or ImplementationType.

String name

Name of the registration

ITypeLifetimeManager lifetimeManager

A lifetime manager that controls how instances are created, managed, and disposed of. If lifetimeManager is null, container uses default Transient lifetime.

InjectionMember[] injectionMembers

Optional injection configuration objects

Returns
Type Description
IUnityContainer

The IUnityContainer object that this method was called on.

Remarks

Container stores registrations by registeredType Type. When resolving, it will look for this Type to satisfy dependencies. Each registration is uniquely identified by registeredType and name. Registering the same Type with different names will create distinct registrations for each Type and name combinations. Registration with no name (name == null) is called default registration. The container uses these as implicit defaults when required.

Type mappedToType will not be registered with the container. It will only be used to inform container how to build the requested instance or where to redirect to satisfy the request. If the type provided in mappedToType is already registered with the container, the registration creates a mapping to the existing registration. It will redirect to that registration when creating an object.

If injectionMembers collection is not empty, the mapping will not redirect to other registrations. Instead, it will always build the Type according to the rules set by provided InjectionMember objects.

Registering a Type with the same name second time will overwrite previous registration. When overwritten, registration will dispose of lifetime manager it was registered with and if that manager holds a reference to an instance of a disposable object (the object implements IDisposable), it will be disposed of as well.

During registration, Unity performs only a limited number of checks. To enable slower but more thorough and detailed validation add Diagnostic extension to the container.

Examples

This example registers a default (no name) singleton service. The service will be created with a default constructor, field and property Resolved and Injected are initialized with resolved and injected values respectively, and method Init is called on the created object.

c.RegisterType(typeof(IService),                         // Type to register
               typeof(Service),                          // Type to create
               null,                                     // Default (no name)
               TypeLifetime.Singleton,                   // Singleton lifetime
               Invoke.Constructor(),                     // Use default ctor
               Invoke.Method(nameof(Service.Init)),      // Call Init(...)
               Resolve.Field(nameof(Service.Resolved))   // Resolve value for Resolved
               Inject.Property(nameof(Service.Injected), // Inject Injected
                                     "value"));          // with constant "value"
Exceptions
Type Condition
InvalidOperationException

If error occur during registration container will throw an exception.

See Also
Inject
Invoke
Resolve
TypeLifetime
| Improve this Doc View Source

Resolve(Type, String, ResolverOverride[])

Resolve an instance of the requested type from the container.

Declaration
object Resolve(Type type, string name, params ResolverOverride[] overrides)
Parameters
Type Name Description
Type type

A Type of object to resolve

String name

Name of the registration

ResolverOverride[] overrides

Overrides for dependencies

Returns
Type Description
Object

The retrieved object.

Remarks

During resolution Unity checks if Type is registered and uses that registration to create an object. If Type is not registered it uses reflection to get information about the Type and creates a pipeline to instantiate and initialize the Type using reflected data.

Resolver overrides passed to the method will only override dependencies configured for injection. For example, if some members were marked with attributes to be injected or registered with associated InjectionMember objects, only these members will be available for overriding. Override values for members not configured for injection will be ignored.

During resolution, Unity performs only a limited number of checks. If any errors occur, error information is very brief. To enable slower but more thorough and detailed validation and expanded error reporting add Diagnostic extension to the container.

Exceptions
Type Condition
ResolutionFailedException

Throws if any errors occur during resolution

See Also
Override

Extension Methods

UnityContainerExtensions.RegisterType<T>(IUnityContainer, InjectionMember[])
UnityContainerExtensions.RegisterType<T>(IUnityContainer, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterType<T>(IUnityContainer, String, InjectionMember[])
UnityContainerExtensions.RegisterType<T>(IUnityContainer, String, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterType<TFrom, TTo>(IUnityContainer, InjectionMember[])
UnityContainerExtensions.RegisterType<TFrom, TTo>(IUnityContainer, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterType<TFrom, TTo>(IUnityContainer, String, InjectionMember[])
UnityContainerExtensions.RegisterType<TFrom, TTo>(IUnityContainer, String, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterSingleton<T>(IUnityContainer, InjectionMember[])
UnityContainerExtensions.RegisterSingleton<T>(IUnityContainer, String, InjectionMember[])
UnityContainerExtensions.RegisterSingleton<TFrom, TTo>(IUnityContainer, InjectionMember[])
UnityContainerExtensions.RegisterSingleton<TFrom, TTo>(IUnityContainer, String, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, String, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, String, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, Type, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, Type, String, InjectionMember[])
UnityContainerExtensions.RegisterType(IUnityContainer, Type, Type, ITypeLifetimeManager, InjectionMember[])
UnityContainerExtensions.RegisterSingleton(IUnityContainer, Type, InjectionMember[])
UnityContainerExtensions.RegisterSingleton(IUnityContainer, Type, String, InjectionMember[])
UnityContainerExtensions.RegisterSingleton(IUnityContainer, Type, Type, InjectionMember[])
UnityContainerExtensions.RegisterSingleton(IUnityContainer, Type, Type, String, InjectionMember[])
UnityContainerExtensions.RegisterInstance<TInterface>(IUnityContainer, TInterface)
UnityContainerExtensions.RegisterInstance<TInterface>(IUnityContainer, TInterface, IInstanceLifetimeManager)
UnityContainerExtensions.RegisterInstance<TInterface>(IUnityContainer, String, TInterface)
UnityContainerExtensions.RegisterInstance<TInterface>(IUnityContainer, String, TInterface, IInstanceLifetimeManager)
UnityContainerExtensions.RegisterInstance(IUnityContainer, Type, Object)
UnityContainerExtensions.RegisterInstance(IUnityContainer, Type, Object, IInstanceLifetimeManager)
UnityContainerExtensions.RegisterInstance(IUnityContainer, Type, String, Object)
UnityContainerExtensions.RegisterFactory<TInterface>(IUnityContainer, Func<IUnityContainer, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory<TInterface>(IUnityContainer, Func<IUnityContainer, Type, String, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory<TInterface>(IUnityContainer, String, Func<IUnityContainer, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory<TInterface>(IUnityContainer, String, Func<IUnityContainer, Type, String, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory(IUnityContainer, Type, Func<IUnityContainer, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory(IUnityContainer, Type, Func<IUnityContainer, Type, String, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory(IUnityContainer, Type, String, Func<IUnityContainer, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.RegisterFactory(IUnityContainer, Type, String, Func<IUnityContainer, Type, String, Object>, IFactoryLifetimeManager)
UnityContainerExtensions.Resolve<T>(IUnityContainer, ResolverOverride[])
UnityContainerExtensions.Resolve<T>(IUnityContainer, String, ResolverOverride[])
UnityContainerExtensions.Resolve(IUnityContainer, Type, ResolverOverride[])
UnityContainerExtensions.ResolveAll(IUnityContainer, Type, ResolverOverride[])
UnityContainerExtensions.ResolveAll<T>(IUnityContainer, ResolverOverride[])
UnityContainerExtensions.BuildUp<T>(IUnityContainer, T, ResolverOverride[])
UnityContainerExtensions.BuildUp<T>(IUnityContainer, T, String, ResolverOverride[])
UnityContainerExtensions.BuildUp(IUnityContainer, Type, Object, ResolverOverride[])
UnityContainerExtensions.IsRegistered(IUnityContainer, Type)
UnityContainerExtensions.IsRegistered<T>(IUnityContainer)
UnityContainerExtensions.IsRegistered<T>(IUnityContainer, String)
InjectionMatching.Matches(Object, Type)
InjectionMatching.MatchesObject(Object, Type)
  • Improve this Doc
  • View Source
In This Article
Back to top Copyright © 2020 .NET Foundation and Contributors. All Rights Reserved