小编And*_*ewG的帖子

使用TinyIoC构造函数注入

我刚从Ninject更改为TinyIoC以进行依赖注入,而我在构造函数注入方面遇到了麻烦.

我已设法将其简化为此代码段:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

这会导致抛出TinyIoCResolutionException:

"Unable to resolve type: TinyIoCTestApp.Foo"
Run Code Online (Sandbox Code Playgroud)

在该异常内部是一系列内部异常:

"Unable to resolve type: TinyIoCTestApp.Bar"
"Unable to resolve type: System.String"
"Unable to resolve type: System.Char[]"
"Value …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection constructor-injection tinyioc

4
推荐指数
1
解决办法
8009
查看次数