我刚刚将依赖注入从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());
}
}这会导致抛出TinyIoCResolutionException,并显示以下内容:
"Unable to resolve type: TinyIoCTestApp.Foo"在该异常内部是一系列内部异常:
"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"我使用构造函数注入的方式有什么问题吗?我意识到我可以打电话给
container.Register<IBar, Bar>(new Bar(value));这确实是有效的,但是结果是一个全局的Bar实例,这不是我想要的。
有什么想法吗?
发布于 2012-02-09 16:48:37
我不熟悉TinyIOC,但我想我可以回答你的问题。
UsingConstructor注册了一个指向构造函数( ctor(string))的lambda,TinyIOC将使用该构造函数进行自动构造函数注入。TinyIOC将分析构造函数参数,找到System.String类型的参数并尝试解析该类型。因为您没有显式地注册System.String (顺便说一下,您不应该这样做),所以解析IBar (以及Foo)会失败。
您所做的错误假设是TinyIOC将执行您的() => new Bar(value)) lambda,但事实并非如此。如果你看一下UsingConstructor方法,你会发现它接受的是Expression<Func<T>>而不是Func<T>。
您需要的是注册一个执行创建的工厂委托。我希望TinyIOC包含一个用于此目的的方法。它可能看起来像这样:
container.Register<IBar>(() => new Bar(value));https://stackoverflow.com/questions/9202899
复制相似问题