简体   繁体   English

温莎城堡-无法将适当的成分注册到浮石中

[英]Castle windsor - Unable to register a proper component with argumants

In a unit test I resolve an interface with sending arguments for its constructor as below: 在单元测试中,我解析了一个接口,并为其构造函数发送自变量,如下所示:

var args = new { arg1 = "arg1 value", arg2 = "arg2 value" };
var component = container.Resolve<IMyDependency>(args);

and it works fine. 而且效果很好。 But now I want to do it in constructor injection, for example in: 但是现在我想在构造函数注入中做到这一点,例如:

public class Foo
{
     private IMyDependency _dep;
     public Foo(IMyDependency dep) { _dep = dep; }
}

So, As a try I register it with UsingFactoyMethod() like this: 因此,尝试将其注册为UsingFactoyMethod()如下所示:

public class BarInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IMyDependency>().UsingFactoryMethod(
                () =>
                {
                    var args = new { arg1 = "arg1 value", arg2 = "arg2 value" };
                    var result = container.Resolve<IMyDependency>(args);
                    return result;
                }).LifestyleTransient());

        // + some other registerations and installs
    }
}

But I have still error: 但是我仍然有错误:

Can't create component 'namespace.MyDependency' as it has dependencies to be satisfied. 无法创建组件“ namespace.MyDependency”,因为它具有要满足的依赖关系。

'namespace.MyDependency' is waiting for the following dependencies: “ namespace.MyDependency”正在等待以下依赖项:
- Parameter 'arg1' which was not provided. -未提供参数“ arg1”。 Did you forget to set the dependency? 您忘记设置依赖项了吗?
- Parameter 'arg2' which was not provided. -未提供参数“ arg2”。 Did you forget to set the dependency? 您忘记设置依赖项了吗?

I think you should try register IMyDependency implementaion with it's constructor args instead of using "UsingFactoyMethod()": 我认为您应该尝试向其构造函数args注册IMyDependency实现,而不是使用“ UsingFactoyMethod()”:

string someArg = "something";
container.Register(
        Component.For<IMyDependency>().ImplementedBy<MyDependencyImp>()
           .DependsOn(Dependency.OnValue("someArg",someArg)).LifestyleTransient());

Assuming MyDependencyImp constructor looks something like this: 假设MyDependencyImp构造函数看起来像这样:

public MyDependencyImp(string someArg)
{
    /....
}

More info here . 更多信息在这里

Do you register IMyDependency anywhere else? 您是否在其他任何地方注册IMyDependency? It's tough to say what's wrong until you post the actual code. 在发布实际代码之前,很难说出问题所在。

This should work: 这应该工作:

container.Register(
        Component.For<IMyDependency>().UsingFactoryMethod(
            () =>
            {
                return new MyDependency("arg1 value", "arg2 value");
            }).LifestyleTransient());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM