Phi*_*Hoy 5 dependency-injection castle-windsor
一些依赖注入容器使您能够将已配置的服务注入已构造的对象.
使用Windsor可以实现这一点,同时考虑到目标对象上可能存在的任何服务依赖性吗?
这是一个古老的问题,但谷歌最近在这里引导我,所以我想我会分享我的解决方案,以免它帮助某人寻找像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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是此方法的简单单元测试:
[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
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3024 次 |
| 最近记录: |