一些依赖注入容器使您能够将配置的服务注入到已经构建的对象中。
这是否可以使用 Windsor 来实现,同时考虑到目标对象上可能存在的任何服务依赖关系?
一些依赖注入容器使您能够将配置的服务注入到已经构建的对象中。
这是否可以使用 Windsor 来实现,同时考虑到目标对象上可能存在的任何服务依赖关系?
这是一个老问题,但谷歌最近把我带到了这里,所以我想我会分享我的解决方案,以免它帮助有人寻找类似 StructureMap 的 Windsor 的 BuildUp 方法。
我发现我可以相对容易地自己添加这个功能。这是一个示例,它只是将依赖项注入到一个对象中,在该对象中它找到了一个空接口类型的属性。当然,您可以进一步扩展概念以查找特定属性等:
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
{
}
}
不,它不能。
正如 Krzysztof 所说,对此没有官方解决方案。不过,您可能想尝试这种解决方法。
就个人而言,我认为必须这样做是一种代码味道。如果是你的代码,为什么没有在容器中注册?如果它不是您的代码,请为它编写一个工厂/适配器/等。