Register and Resolve a Func<> with TinyIoc

726 Views Asked by At

I am trying to register a Func<string> with TinyIoc.:

container.Register<Func<string>>(() => myObject.MyProperty); 

and a type that depends on it with a constructor:

MyDependentType(Func<string> function)

when I use

container.Resolve<MyDependentType>()

it's all fine, but i cannot register a second Func<string> because it can not be resolved. It's ambigious I guess. No Error is thrown, but the injected Func is the wrong one. I tried to add names, no success.

Does TinyIoc actually support that? Or do I have to wrap my functions into objects? Like strategy pattern?

2

There are 2 best solutions below

1
NightOwl888 On BEST ANSWER

You are right, it is ambiguous to map the same type more than once. No DI container can handle this, because there is no way to tell one Func<string> from another Func<string>.

That said, your usage example seems really unusual. Normally, if you want a property inside of another object, you inject the object that property belongs to, not a Func<string>.

class MyObject : IMyObject
{
    public string MyProperty { get { return "foo"; } }
}

class MyDependentType : IMyDependentType
{
    private readonly IMyObject myObject;

    public MyDependentType(IMyObject myObject)
    {
        this.myObject = myObject;
    }

    public void DoSomething()
    {
        var myProperty = this.myObject.MyProperty;
        // do something with myProperty...
    }
}
0
HankTheTank On

Like NightOwl888 said, those Func<> objects are ambiguous. In the end I used a factory lambda.

container.Register<IMyType>((c, o) => {
    var dep = c.Resolve<IDependentType>();
    return new MyConcreteClass(() => dep.DependantFunc);
});

It's a bit much, but now I can let TinyIoc resolve my dependencies. I just have to create the factory lambda.