温莎城堡注入构造对象的属性

时间:2009-05-12 09:30:11

标签: dependency-injection castle-windsor

一些依赖注入容器使您能够将已配置的服务注入已构造的对象中。

可以使用Windsor实现这一点,同时考虑目标对象上可能存在的任何服务依赖性吗?

3 个答案:

答案 0 :(得分:9)

这是一个古老的问题,但谷歌最近在这里引导我,所以我想我会分享我的解决方案,以免它帮助某人寻找类似于WindMap的StructureMap的BuildUp方法。

我发现我可以相对轻松地添加此功能。下面是一个示例,它只是将依赖项注入到一个对象中,在该对象中找到一个null接口类型的属性。您可以进一步扩展概念,以寻找特定的属性等:

public static void InjectDependencies(this object obj, IWindsorContainer container)
{
    var type = obj.GetType();
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var property in properties)
    {
        if (property.PropertyType.IsInterface)
        {
            var propertyValue = property.GetValue(obj, null);
            if (propertyValue == null)
            {
                var resolvedDependency = container.Resolve(property.PropertyType);
                property.SetValue(obj, resolvedDependency, null);
            }
        }
    }
}

以下是此方法的简单单元测试:

[TestFixture]
public class WindsorContainerExtensionsTests
{
    [Test]
    public void InjectDependencies_ShouldPopulateInterfacePropertyOnObject_GivenTheInterfaceIsRegisteredWithTheContainer()
    {
        var container = new WindsorContainer();
        container.Register(Component.For<IService>().ImplementedBy<ServiceImpl>());

        var objectWithDependencies = new SimpleClass();
        objectWithDependencies.InjectDependencies(container);

        Assert.That(objectWithDependencies.Dependency, Is.InstanceOf<ServiceImpl>());
    }

    public class SimpleClass
    {
        public IService Dependency { get; protected set; }
    }

    public interface IService
    {
    }

    public class ServiceImpl : IService
    {
    }
}

答案 1 :(得分:5)

不,它不能。

答案 2 :(得分:1)

正如Krzysztof所说,没有正式的解决方案。您可能想尝试this workaround

就个人而言,我认为必须这样做一个代码味道。如果是您的代码,为什么不在容器中注册?如果它不是您的代码,请为它编写工厂/适配器/等。