一些依赖注入(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/