Skip to content

Simplified parametric Func-based injection #91

@Serg046

Description

@Serg046

Consider you have a service that should receive some dependency at runtime:

class Foo(string runtimeArg, IBar bar) : IFoo {}
class Baz(Func<string, IFoo> factory) {
    var foo1 = factory("1");
    var foo2 = factory("2");
}

The only current way to achieve it is to do something like this which is rather verbose. Another disadvantage is that you will have to register your argument for the whole composition root with either the name or tag so that it could be linked into another service unexpectedly.

DI.Setup()
    .Bind<IBar>().To<Bar>()
    .Bind<string>().To<string>("runtimeArg")
    .Bind<Func<string, IFoo>>().To<Func<string, IFoo>>(ctx => runtimeArg => {
        ctx.Inject<Foo>(out var foo);
        return foo;
    })

The proposal is to make it less verbose. Ideally you want to map IFoo to Foo without any additional steps required like it is usually done in classic dynamic containers without checks.

DI.Setup()
    .Bind<IBar>().To<Bar>()
    // 1. This will obviously fail referring to runtimeArg, we should keep it
    // .Bind<IFoo>().To<Foo>()
    // 2. This will complain that Func<string, IFoo> is not implemented by Func<string, Foo>
    // .Bind<Func<string, IFoo>>().To<Func<string, Foo>>()
    // 3. Some syntax like this could work
    .Bind<IFoo>().AsFunc().To<Foo>() // or AsFactory(), or AsFunc<string>() or just something similar

The hint will tell the gen to do the following:

  1. Get the dependency list [string,IBar].
  2. Scan the composition to see if there are registered deps [IBar].
  3. Exclude registered deps from the list [string].
  4. Register a func of service with remaining deps instead of the initial service. Func<string, IFoo> instead of IFoo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions