Castle Windsor advanced factory registration

笑着哭i 提交于 2019-12-11 03:42:00

问题


having the class:

public class SomeClass{
     public SomeClass(IBlabla bla, string name){
         //....
     }
}

I can write factory:

public class SomeClassFactory{
public SomeClassFactory(IBlabla bla){
         //....
     }
    public SomeClass Create(string name){return new SomeClass(_bla, name)}
}

And live with it. But I wonder, is there any solution to do this without such obvious factory implementation, in the same way as .AsFactory() works, but with additional parameter?


回答1:


Definitely possible, and you can even do it without an implementation through the typed factories in Castle. Here is how :

Given your base classes:

public interface IBlabla
{
}

public class Blabla : IBlabla
{
}

public class SomeClass
{
    public string Name { get; set; }
    public IBlabla Blabla { get; set; }
    public SomeClass(IBlabla bla, string named)
    {
        Blabla = bla;
        Name = named;
    }
}

you can create a generic factory for elements with a string named in their constructor:

public interface IFactory
{
    T Build<T>(string named);
}

No need for any implementation, you are going to use a tool that will create an automatic implementation of your factory backed up by Castle:

// container
var container = new Castle.Windsor.WindsorContainer(); 
// factory facility, needed to add behavior
container.AddFacility<TypedFactoryFacility>(); 
// let's register what we need
container.Register(
        // your factory interface
        Component.For<IFactory>().AsFactory(),
        // your IBlabla
        Component.For<IBlabla>().ImplementedBy<Blabla>(),
        // component, you could register against an interface
        Component.For<SomeClass>().ImplementedBy<SomeClass>()
    );
// shazam, let's build our SomeClass
var result = container.Resolve<IFactory>().Build<SomeClass>("bla?");

Why does it work? When going through a typed factory, Castle will try and hand the object being resolved all the parameters that are passed to the factory call. So the named parameter is given to the constructor of your SomeClass. The IBlabla is resolved through standard behavior for Castle.

There you are, factory without any implementation are neat :D



来源:https://stackoverflow.com/questions/24574784/castle-windsor-advanced-factory-registration

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