Interface IUnityContainer
- Namespace
- Unity
- Assembly
- Unity.Abstractions.dll
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.
[CLSCompliant(true)]
public interface IUnityContainer : IDisposable
- Inherited Members
- Extension Methods
-
UnityContainerExtensions.RegisterType(IUnityContainer, Type, Type, string, params InjectionMember[])
Properties
Parent
The parent of this container.
IUnityContainer Parent { get; }
Property Value
- 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.
Registrations
Lists all registrations available at this container.
IEnumerable<IContainerRegistration> Registrations { get; }
Property Value
- 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
Methods
BuildUp(Type, object, string, params ResolverOverride[])
Run an existing object through the build pipeline and perform injections on it
object BuildUp(Type type, object existing, string name, params ResolverOverride[] overrides)
Parameters
type
TypeType of object to perform injection on.
existing
objectInstance to the object.
name
stringname to use when looking up the registration and other configurations.
overrides
ResolverOverride[]Any overrides for the resolve calls.
Returns
- 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 withtype
).
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
- ResolutionFailedException
Throws if any errors occur during initialization
- See Also
CreateChildContainer()
Create a child container.
IUnityContainer CreateChildContainer()
Returns
- 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.
IsRegistered(Type, string)
Checks if Type is registered with container
bool IsRegistered(Type type, string name)
Parameters
Returns
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.
RegisterFactory(Type, string, Func<IUnityContainer, Type, string, object>, IFactoryLifetimeManager)
Register Type factory with the container
IUnityContainer RegisterFactory(Type type, string name, Func<IUnityContainer, Type, string, object> factory, IFactoryLifetimeManager lifetimeManager)
Parameters
type
TypeRegistration Type. A Type the factory will create when requested
name
stringRegistration name
factory
Func<IUnityContainer, Type, string, object>Predefined factory delegate
lifetimeManager
IFactoryLifetimeManagerThe FactoryLifetime that controls the lifetime of objects. If
lifetimeManager
isnull
, container uses default Transient lifetime
Returns
- IUnityContainer
The IUnityContainer object that this method was called on.
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
Remarks
This method allows registration of factory function for specific Type.
This registration is very similar to RegisterType(Type, Type, string, ITypeLifetimeManager, params 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.
Exceptions
- InvalidOperationException
If delegate is
null
method throws
- See Also
RegisterInstance(Type, string, object, IInstanceLifetimeManager)
Register an instance with the container.
IUnityContainer RegisterInstance(Type type, string name, object instance, IInstanceLifetimeManager lifetimeManager)
Parameters
type
TypeRegistration Type. This parameter could be either
null
or any of the interface types the instance implements. Iftype
isnull
the instance will be registered by its Typename
stringRegistration name
instance
objectThe Object to be registered
lifetimeManager
IInstanceLifetimeManagerAn InstanceLifetime manager that controls the lifetime. If no manager is provided (
lifetimeManager == null
) container uses PerContainer lifetime by default
Returns
- IUnityContainer
The IUnityContainer object that this method was called on.
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
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.
Exceptions
- InvalidOperationException
If types of registration and the instance are not assignable, method throws an exception
- See Also
RegisterType(Type, Type, string, ITypeLifetimeManager, params InjectionMember[])
Register a type or a type mapping with the container.
IUnityContainer RegisterType(Type registeredType, Type mappedToType, string name, ITypeLifetimeManager lifetimeManager, params InjectionMember[] injectionMembers)
Parameters
registeredType
TypeRegistration Type. This Type will be requested when resolving. Sometimes referred as
FromType
orServiceType
mappedToType
TypeA Type that will actually be returned. Also referred as
ToType
orImplementationType
.name
stringName of the registration
lifetimeManager
ITypeLifetimeManagerA lifetime manager that controls how instances are created, managed, and disposed of. If
lifetimeManager
isnull
, container uses default Transient lifetime.injectionMembers
InjectionMember[]Optional injection configuration objects
Returns
- IUnityContainer
The IUnityContainer object that this method was called on.
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"
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.
Exceptions
- InvalidOperationException
If error occur during registration container will throw an exception.
- See Also
Resolve(Type, string, params ResolverOverride[])
Resolve an instance of the requested type from the container.
object Resolve(Type type, string name, params ResolverOverride[] overrides)
Parameters
type
TypeA Type of object to resolve
name
stringName of the registration
overrides
ResolverOverride[]Overrides for dependencies
Returns
- 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
- ResolutionFailedException
Throws if any errors occur during resolution
- See Also