Can Castle.Windsor TypedFactoryFacility construct a type with only some ref arguments passed inline?

此生再无相见时 提交于 2019-12-23 20:07:14

问题


I have hit a problem in my use of Castle.Windsor's TypedFactoryFacility concept, and not sure how to resolve it (or if I can).

I have a ViewModel defined like so;

public class MyViewModel : IMyViewModel
{
    // constructor which I aim to access through the factory
    public MyViewModel(
        ISomeContainerResolvableDependency a,
        ISomePassedInDependency b)
    { ... }
}

And a corresponding factory interface defined like;

public interface IMyViewModelFactory 
{
    IMyViewModel Create(ISomePassedInDependency a);

    void Release(IMyViewModel vm);
}

However, when I try to call the factory with a valid, non-null instance of ISomePassedInDependency like so;

ISomePassedInDependency o = new SomePassedInDependency();
IMyViewModelFactory factory = IoC.Get<IMyViewModelFactory>();
IMyViewModel viewModel = factory.Create(o);

I get an Exception stating that Castle Windsor could not resolve the dependency from IMyViewModel on ISomePassedInDependency. In this case, I am supplying the ISomePassedInDependency instance, and only want the facility to resolve ISomeContainerResolvableDependency for me.

If I change the constructor definition to accept a value type which I pass in (int, for example) instead of an ISomePassedInDependency instance, the factory call works. So, it seems that there is an assumption inside Castle Windsor that all reference types will be container resolved and anything else will not?

Is there some way to make this work?


回答1:


OK, I re-read the documentation and noticed a key piece of info I had overlooked; the argument names in the factory must match the argument names in the object being instantiated.

So, in my example above, if the constructor of the ViewModel is changed to;

public MyViewModel(
    ISomeContainerResolvableDependency x,
    ISomePassedInDependency a) // <-- NOTE this argument is now named 'a' to match the factory definition
{ ... }    

It works.

Magic.



来源:https://stackoverflow.com/questions/19170743/can-castle-windsor-typedfactoryfacility-construct-a-type-with-only-some-ref-argu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!