5

一部の依存性注入コンテナを使用すると、構成済みのサービスをすでに構築されているオブジェクトに注入できます。

これは、ターゲットオブジェクトに存在する可能性のあるサービスの依存関係を考慮しながら、Windsorを使用して実現できますか?

4

3 に答える 3

9

これは古い質問ですが、Googleが最近私をここに導いてくれたので、StructureMapのWindsor用の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
    {
    }
}
于 2011-06-08T09:52:05.793 に答える
5

いいえ、できません。

于 2009-05-12T12:13:02.987 に答える
1

Krzysztofが言ったように、これに対する公式の解決策はありません。ただし、この回避策を試してみることをお勧めします。

個人的には、これをコードの臭いにする必要があると思います。それがあなたのコードなら、なぜそれはコンテナに登録されないのですか?コードでない場合は、ファクトリ/アダプタなどを記述してください。

于 2009-05-12T14:38:47.547 に答える