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

1

3

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?

Sitton answered 3/10, 2013 at 23:22 Comment(0)
S
5

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.

Sitton answered 3/10, 2013 at 23:46 Comment(1)
That helped a lot. I was really scratching my head on this one. ThanksBueschel

© 2022 - 2024 — McMap. All rights reserved.