城堡温莎先进的工厂登记 [英] Castle Windsor advanced factory registration

查看:141
本文介绍了城堡温莎先进的工厂登记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有类:

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)}
}

和忍受它。但我不知道,有没有什么解决办法做到这一点没有这种明显的工厂实现,以同样的方式为.AsFactory()的作品,但额外的参数?

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?

推荐答案

绝对有可能,你甚至可以做到这一点没有通过的输入工厂的城堡。方法如下:

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

由于基类:

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?");

为什么要工作?当通过类型化的工厂去,城堡将尝试与手头上的物体被解决了所有被传递到工厂调用的参数。因此,名为参数给的构造你的 SomeClass的。该 IBlabla 通过对城堡标准行为解决。

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.

你来了,工厂没有任何实现整洁:D

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

这篇关于城堡温莎先进的工厂登记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆