0

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?

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
HankTheTank
  • 537
  • 5
  • 15
  • This question will need some more context to provide an answer. The only concrete solution I can come up with based on the info provided is to create a factory class and interface to replace each `Func`. Many consider lots of factories to be a code smell. [Strategy](https://stackoverflow.com/a/31971691) works if the caller (or the ambient context) knows what property it is looking for, but that is unclear from the question. – NightOwl888 Feb 10 '18 at 01:06

2 Answers2

1

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...
    }
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • The use case might be unusual. But we need it for a pattern we are using with WPF and commands. It's decoupling the command from the view model. But this is not the issue here. Long story short, we need it. Looks like I need another solution – HankTheTank Feb 09 '18 at 18:45
0

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.

HankTheTank
  • 537
  • 5
  • 15