问题
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