Constructor Injection with TinyIoC

I just changed from Ninject to TinyIoC for dependency injection, and I'm having trouble introducing the constructor.

I managed to simplify it 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 throws a TinyIoCResolutionException:

 "Unable to resolve type: TinyIoCTestApp.Foo" 

and inside this exception there is a chain of internal 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 how I use constructor injection? I understand that I can call

 container.Register<IBar, Bar>(new Bar(value)); 

and it really works, however the result is a global instance of Bar, which is not what I need.

Any ideas?

+4
source share
1 answer

I am not familiar with TinyIOC, but I think I can answer your question.

UsingConstructor registers a lambda that points to the constructor ( ctor(string) ) that TinyIOC will use to automatically insert the constructor. TinyIOC will parse the constructor arguments, find an argument of type System.String and try to resolve this type. Since you did not register System.String explicitly (that you do not need btw), resolving IBar (and therefore Foo ) fails.

The wrong assumption you made is that TinyIOC will execute your () => new Bar(value)) lambda, which it won't be. If you look at the UsingConstructor method that you can use, see Expression<Func<T>> instead of Func<T> .

The thing you want is to register the factory delegate that creates the creation. I expect TinyIOC to contain a method for this. It might look something like this:

 container.Register<IBar>(() => new Bar(value)); 
+7
source

Source: https://habr.com/ru/post/1395513/


All Articles