I have just changed from Ninject to TinyIoC for dependency injection and I'm having trouble with constructor injection.
I have managed to simplify it down to this snippet:
public interface IBar { }
public class Foo
{
public Foo(IBar bar) { }
}
public class Bar : IBar
{
public Bar(string value) { }
}
class Program
{
static void Main(string[] args)
{
var container = TinyIoCContainer.Current;
string value = "test";
container.Register<IBar, Bar>().UsingConstructor(() => new Bar(value));
var foo = container.Resolve<Foo>();
Console.WriteLine(foo.GetType());
}
}
which causes a TinyIoCResolutionException to be thrown with:
"Unable to resolve type: TinyIoCTestApp.Foo"
and inside that exception is a chain of inner exceptions:
"Unable to resolve type: TinyIoCTestApp.Bar"
"Unable to resolve type: System.String"
"Unable to resolve type: System.Char[]"
"Value cannot be null.\r\nParameter name: key"
Is there something wrong with the way I'm using the constructor injection? I realize I could call
container.Register<IBar, Bar>(new Bar(value));
and that does indeed work, however the result is a global instance of Bar which is not what I'm after.
Any ideas?
I'm not familiar with TinyIOC, but I think I can answer your question.
The
UsingConstructor
registers a lambda that points at a constructor (thector(string)
) that TinyIOC will use to do automatic constructor injection into. TinyIOC will analyse the constructor arguments, finds an argument of typeSystem.String
and tries to resolve that type. Since you haven't registeredSystem.String
explicitly (which you shouldn't btw), resolvingIBar
(and thusFoo
) fails.The incorrect assumption you made is that TinyIOC will execute your
() => new Bar(value))
lambda, which it will not. If you look at theUsingConstructor
method you will propable see that it takes anExpression<Func<T>>
instead of aFunc<T>
.The thing you want, is to register a factory delegate that does the creation. I expect TinyIOC to contain a method for this. It might look something like this: