我之前从未使用过Windsor,但是使用过其他DI框架,目前我有一个相当奇怪的问题。
我有一个工厂类,它在构造函数中接受一个字符串,但是每当我尝试解析该对象时,我都会得到一个例外:
Handler for System.String was not found.
<Message>Handler for System.String was not found.</Message>
<StackTrace>at Castle.MicroKernel.Resolvers.DefaultDependencyResolver
.TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context)
in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 403
at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ComponentModel model, DependencyModel dependency) in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 270</StackTrace>
<Type>Castle.MicroKernel.Handlers.HandlerException</Type>
</InnerException>
<Message>Missing dependency.
Component SomeExampleFactory has a dependency on System.String, which could not be
resolved.
Make sure the dependency is correctly registered in the container as a service, or
provided as inline argument.</Message>
该课程类似于:
public interface IDummyFactory
{
void DoSomething();
}
public class DummyFactory : IDummyFactory
{
private string someString;
public DummyFactory(string someConstructorArg)
{
someString = someConstructorArg;
}
}
使用以下DI设置:
var someString = "some constructor arg";
_container.Register(Component.For<IDummyFactory>()
.ImplementedBy<DummyFactory>()
.DependsOn(someString));
我假设它正在尝试进行某种类型的转换或格式化导致它炸弹,但由于类型本身是一个字符串,而变量是以字符串形式传递的......它甚至可能是它试图映射该变量的类型而不是变量内容,但我对DI框架和该区域的文档知之甚少
答案 0 :(得分:10)
我一直在寻找这个问题的答案,看起来他们现在有一些更简单的东西,他们称之为“内联依赖关系”,它通过(以及其他方式)Dependency.OnValue()方法实现。
以下是文档中的通用示例:
var twitterApiKey = @"the key goes here";
container.Register(
Component.For<ITwitterCaller>().ImplementedBy<MyTwitterCaller>()
.DependsOn(Dependency.OnValue("APIKey", twitterApiKey))
);
它将使用 twitterApiKey 中的值作为名称为“APIKey”(不区分大小写)的参数。
https://github.com/castleproject/Windsor/blob/master/docs/inline-dependencies.md
看起来这可能已经从版本3.1开始了,但我无法完全解读他们的更新标记约定。
答案 1 :(得分:8)
尝试调用DependsOn
的重载,该重载需要IDictionary
个键/值对来指定依赖项:
_container.Register(
Component.For<IDummyFactory>()
.ImplementedBy<DummyFactory>()
.DependsOn(new Hashtable
{
{ "someConstructorArg", "some constructor arg" }
}));