Skip to content
This repository has been archived by the owner on Oct 2, 2019. It is now read-only.

Factory

Bruno Juchli edited this page Apr 11, 2016 · 3 revisions

This feature converts interfaces into factory implementations. The proxy is weaved during compilation, the interpretation of the factory interface takes place during runtime.

Usage

Bind any interface (marked with [StaticProxy]-attribute) as follows:

using Ninject.Extensions.StaticProxy.Factory;

Bind<IFactory>().ToFactory();

Basic Example

[StaticProxy]
public interface IFactory
{
    IFoo Create(string parameter);
}

returns the result of the following resolution:

kernel.Get<IFoo>(new TypeMatchingConstructorArgument(
    typeof(string), (ctx, target) => parameter, false));

Parameter Injection

Inject Constructor Argument Matching a Type

[StaticProxy]
public interface IFactory
{
    IFoo Create([TypeMatchingConstructorArgument(inherited:true)] string parameter);
}

returns the result of the following resolution:

kernel.Get<IFoo>(new TypeMatchingConstructorArgument(
    typeof(string), (ctx, target) => parameter, true));

Inject Constructor Argument Matching a Parameter Name

[StaticProxy]
public interface IFactory
{
    IFoo Create([NamedConstructorArgument(inherited:true)] string parameter);
}

factory.Create("Hallo");

returns the result of the following resolution:

kernel.Get<IFoo>(new ConstructorARgument("parameter", "Hallo", true));

Specifying what type to resolve

[StaticProxy]
public interface ITransportFactory
{
    [ResolveTo(typeof(TcpTransport))]
    ITransport CreateTcpTransport();
}

returns the result of the following resolution:

kernel.Get<TcpTransport>();

Constrained Resolution

Hint: If a factory-method has multiple constraints (imagine custom constraints), the binding matching all the constraints is chosen.

Constant Named Constraint

[StaticProxy]
public interface IFactory
{
    [NamedConstraint("Bar")]
    IFoo Create();
}

returns the result of the following resolution:

kernel.Get<IFoo>("Bar");

Named Constraint by Parameter

[StaticProxy]
public interface IFactory
{
    IFoo Create([NamedConstraintByParameter]string name);
}

factory.Create("Foo");

returns the result of the following resolution:

kernel.Get<IFoo>("Foo");

Customizing Resolution

You can create and apply custom attributes to customize the resolution. Inherit from any of the following:

  • ReturnTypeAttribute - apply on method
  • ConstraintAttribute - apply on method
  • ParameterisedConstraintAttribute - apply on parameter
  • ParameterAttribute - apply on parameter