Skip to content

Latest commit

 

History

History
121 lines (97 loc) · 2.92 KB

oncannotresolve-hint.md

File metadata and controls

121 lines (97 loc) · 2.92 KB

OnCannotResolve hint

CSharp

Hints are used to fine-tune code generation. The OnCannotResolve hint determines whether to generate a partial OnCannotResolve<T>(...) method to handle a scenario where an instance which cannot be resolved. In addition, setup hints can be comments before the Setup method in the form hint = value, for example: // OnCannotResolveContractTypeNameRegularExpression = string.

using static Hint;

interface IDependency;

class Dependency(string name) : IDependency
{
    public override string ToString() => name;
}

interface IService
{
    IDependency Dependency { get; }
}

class Service(IDependency dependency) : IService
{
    public IDependency Dependency { get; } = dependency;
}

partial class Composition
{
    [SuppressMessage("Performance", "CA1822:Mark members as static")]
    private partial T OnCannotResolve<T>(
        object? tag,
        Lifetime lifetime)
    {
        if (typeof(T) == typeof(string))
        {
            return (T)(object)"Dependency with name";
        }

        throw new InvalidOperationException("Cannot resolve.");
    }
}

// OnCannotResolveContractTypeNameRegularExpression = string
DI.Setup(nameof(Composition))
    .Hint(OnCannotResolve, "On")
    .Bind().To<Dependency>()
    .Bind().To<Service>()
    .Root<IService>("Root");

var composition = new Composition();
var service = composition.Root;
service.Dependency.ToString().ShouldBe("Dependency with name");

The OnCannotResolveContractTypeNameRegularExpression hint helps define the set of types that require manual dependency resolution. You can use it to specify a regular expression to filter the full type name. For more hints, see this page.

The following partial class will be generated:

partial class Composition
{
  private readonly Composition _root;

  [OrdinalAttribute(20)]
  public Composition()
  {
    _root = this;
  }

  internal Composition(Composition parentScope)
  {
    _root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
  }

  public IService Root
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      string transientString2 = OnCannotResolve<string>(null, Lifetime.Transient);
      return new Service(new Dependency(transientString2));
    }
  }


  private partial T OnCannotResolve<T>(object? tag, Lifetime lifetime);
}

Class diagram:

classDiagram
	class Composition {
		<<partial>>
		+IService Root
	}
	class String
	Dependency --|> IDependency
	class Dependency {
		+Dependency(String name)
	}
	Service --|> IService
	class Service {
		+Service(IDependency dependency)
	}
	class IDependency {
		<<interface>>
	}
	class IService {
		<<interface>>
	}
	Composition ..> Service : IService Root
	Dependency *--  String : String
	Service *--  Dependency : IDependency
Loading