构造注射TinyIoC [英] Constructor Injection with TinyIoC

查看:380
本文介绍了构造注射TinyIoC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从Ninject改为TinyIoC依赖注入和我在使用构造器注入的麻烦。

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());
    }
}



这会导致TinyIoCResolutionException与抛出:

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.

任何想法?

推荐答案

我不熟悉TinyIOC,但我想我可以回答你的问题。

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

UsingConstructor 注册一个指向一个构造函数的lambda(即构造函数(字符串))这TinyIOC将用做自动构造注入。 TinyIOC将分析构造函数的参数,发现键入 System.String 的参数,并尝试解决该类型。既然你还没有注册 System.String 明确(你不应该BTW),解决伊巴尔(因而)失败。

The UsingConstructor registers a lambda that points at a constructor (the ctor(string)) that TinyIOC will use to do automatic constructor injection into. TinyIOC will analyse the constructor arguments, finds an argument of type System.String and tries to resolve that type. Since you haven't registered System.String explicitly (which you shouldn't btw), resolving IBar (and thus Foo) fails.

您做出不正确的假设是,TinyIOC将执行你的( )= GT;新的酒吧(值))拉姆达,它不会。如果你看看 UsingConstructor 的方法,你propable看到,它需要一个表达式来; Func键< T>> 而不是的 Func键< T>

The incorrect assumption you made is that TinyIOC will execute your () => new Bar(value)) lambda, which it will not. If you look at the UsingConstructor method you will propable see that it takes an Expression<Func<T>> instead of a Func<T>.

你想要的东西,是要注册一个工厂的委托,做创作。 。我希望TinyIOC包含此方法。它看起来是这样的:

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:

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

这篇关于构造注射TinyIoC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆