dependency-injection - 温莎城堡注入(inject)构造对象的属性

标签 dependency-injection castle-windsor

一些依赖注入(inject)容器使您能够将配置的服务注入(inject)到已经构建的对象中。

这是否可以使用 Windsor 来实现,同时考虑到目标对象上可能存在的任何服务依赖关系?

最佳答案

这是一个老问题,但谷歌最近把我带到了这里,所以我想我会分享我的解决方案,以免它帮助有人寻找类似 StructureMap 的 Windsor 的 BuildUp 方法。

我发现我可以相对容易地自己添加这个功能。这是一个示例,它只是将依赖项注入(inject)到一个对象中,在该对象中它找到了一个空接口(interface)类型的属性。当然,您可以进一步扩展概念以查找特定属性等:

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

关于dependency-injection - 温莎城堡注入(inject)构造对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/851940/

相关文章:

Java - 仅在没有字段@Autowired的 super 构造函数中注入(inject)bean

java - 在 Spring 中注入(inject)不同 bean 的多个实例

inversion-of-control - IoC (Windsor) - 什么是 "Default Interface"?

java - 将 java javax.inject.Provider 与 Spring @Scope(BeanDefinition.SCOPE_PROTOTYPE) 一起使用

java - Guice 3.0 - 对于仅具有依赖注入(inject)的 Swing 应用程序,我需要哪些 jar?

symfony - 在服务中注入(inject) Doctrine Entity Manager - 不好的做法?

c# - 我如何对我的 Controller 进行单元测试以确保 Windsor 在使用 PerWebRequestLifestyle 时可以解决依赖关系

c# - 使用 ASP MVC 和 CaSTLe Windsor 将数据库注入(inject)验证属性

c# - CaSTLe Windsor 注册类带有构造函数参数

dependency-injection - 无实现类型工厂问题