Skip to content

Factory interface: custom instance providers

Scott Xu edited this page Apr 7, 2014 · 5 revisions

Factory interface: Custom instance providers

In some cases the default generated instance provider may not meet your exact requirements. In this circumstance, you can create your own implementation with customised behavior. This is achieved by implementing the IInstanceProvider interface:

/// <summary>
/// Provides instances to the interceptor.
/// </summary>
public interface IInstanceProvider
{
    /// <summary>
    /// Gets an instance for the specified method and arguments.
    /// </summary>
    /// <param name="instanceResolver">The instance resolver.</param>
    /// <param name="methodInfo">The method info of the method that was called on the factory.</param>
    /// <param name="arguments">The arguments that were passed to the factory.</param>
    /// <returns>The newly created instance.</returns>
    object GetInstance(IInstanceResolver instanceResolver, MethodInfo methodInfo, object[] arguments);
}

In most cases it is easier to derive from the StandardInstanceProvider and override the required methods to effect the desired behavior. The provider implements GetInstance() for you and handles the the special cases of IEnumerable, ICollection, IList and Arrays for you and in turn declares the following methods that can be overriden to control the type, parameters, name and constraints used to resolve the instance:

Method Comment
Type GetType(
    MethodInfo methodInfo, 
    object[] arguments)
This method can be used to override the default behavior convention: the resolved type is the return type of the executed method.
string GetName(
    MethodInfo methodInfo, 
    object[] arguments)
Used to override the default naming convention: The default behavior is described in [the previous section](Factory interface - Named Bindings).
ConstructorArgument[] GetConstructorArguments(
    MethodInfo methodInfo, 
    object[] arguments)
Used to override the default convention for inferring resolution parameters: The default implementation creates a `ConstructorArgument` with the name taken directly from the name of the factory method parameter.
Func GetConstraint(
    MethodInfo methodInfo, 
    object[] arguments)
Used to introduce a constraint into the resolution process: The default implementation doesn’t impose any constraints.