Skip to content

Factory interface: custom instance providers

remogloor edited this page Feb 29, 2012 · 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:

```text
/// 
/// Provides instances to the interceptor.
/// 
public interface IInstanceProvider
{
    /// 
    /// Gets an instance for the specified method and arguments.
    /// 
    /// The instance resolver.
    /// The method info of the method that was called on the factory.
    /// The arguments that were passed to the factory.
    /// The newly created instance.
    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 the GetInstance method 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.

Clone this wiki locally