简体   繁体   English

温莎城堡对象工厂“ GetByName”注入属性

[英]Windsor Castle object factory “GetByName” injecting properties

I use Castle Windsor in my c# project for DI and I've this scenario: 我在我的C#项目中使用Castle Windsor进行DI,我有这种情况:

public class Class1:IMyClass
{
     public string Name{get{return "Class1";}}
     public int Version {get; set;}
     private string _description;

     public Class1(string description)
     {
        this._description=description;
     }
}
public class Class2:IMyClass
{
     public string Name{get{return "Class2";}}
     public int Version {get; set;}
     private string _description;

     public Class2(string description)
     {
        this._description=description;
     }
}

I can register those classes by the common IMyClass interface but now I need a factory for create a determinated instance; 我可以通过通用的IMyClass接口注册这些类,但是现在我需要一个工厂来创建一个确定的实例。 something like this: 像这样的东西:

IMyClass _myClass= someClassFactory.GetByName("Class2", version=1, description="test");

Is there an example for a factory that resolves a component by name and inject properties and/or constructor values? 是否有一个工厂示例,该工厂通过名称解析组件并注入属性和/或构造函数值?

Absolutely right Cristiano. 完全正确的克里斯蒂亚诺。 Here a bit more info. 这里有更多信息。 No matter how you write your factory you will not be able to create component based on the Name property. 无论您如何编写工厂,都将无法基于Name属性创建组件。 The reason for this is that the property is only availble after creating the object, and the factory needs it before that. 原因是该属性仅在创建对象后可用,而工厂在此之前需要它。

Create a factory : 创建工厂:

interface ISomeClassFactory 
{
    IMyClass GetById(string name, int version, string description);
}

and a selector (copied from: http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx ) 和一个选择器(复制自: http : //docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx

public class CustomTypedFactoryComponentSelector : DefaultTypedFactoryComponentSelector
{
    protected override string GetComponentName(MethodInfo method, object[] arguments)
    {
        if(method.Name == "GetById" && arguments.Length == 1 && arguments[0] is string)
        {
            return (string)arguments[0];
        }
        return base.GetComponentName(method, arguments);
    }
}

And register these as follows: 并按以下方式注册:

Component.For<IMyClass>().ImplementedBy<Class1>().Named("Class1"),
Component.For<IMyClass>().ImplementedBy<Class2>().Named("Class2")
Component.For<IISomeClassFactory>().AsFactory(c=> new CustomTypedFactoryComponentSelector())

Also make sure to add the TypedFactoryFacility to the container. 还要确保将TypedFactoryFacility添加到容器中。

解决方案再次是Typed factory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM