1

依存性注入には Ninject を使用します。ドメイン オブジェクトが IThing である、自由形式で解釈される DDD を使用してコードを設計しています。

次のコードでは、IThing インスタンスを使用して IThingControl を取得する方法を教えてください。

interface IThing {}
class Thing : IThing {}

interface IThingControl<T> where T:IThing {}
class ThingControl<Thing> {}

class Module : NinjectModule {
    public override void Load() {
        Bind<IThingControl<Thing>>().To<ThingControl>();
    }
}

class SomewhereInCode {
    void AddControls() {
        List<IThing> things = new List<IThing> {
            new Thing()
        };
        foreach (IThing thing in things) {
            IThingControl<IThing> control = _kernel.Get(); // <----- eh?
            this.Controls.Add(control);
        }
    }
}
4

2 に答える 2

3

MakeGenericType( here )を使用してインスタンスを取得できますが、キャストすることはできませんIThingControl<IThing>

interface IThing { }
class Thing1 : IThing { }
class Thing2 : IThing { }
interface IThingControl<T> where T : IThing { }
class ThingControl<Thing> { }

class Module : NinjectModule {
    public override void Load()
    {
        Bind(typeof(IThingControl<>)).To(typeof(ThingControl<>));
    }
}

[TestFixture]
public class SomewhereInCode
{
    [Test]
    public void AddControls()
    {
        IKernel kernel = new StandardKernel(new Module());
        List<IThing> things = new List<IThing> { new Thing1(), new Thing2() };
        Type baseType = typeof(IThingControl<>);

        foreach (IThing thing in things)
        {
            Type type = baseType.MakeGenericType(thing.GetType());
            dynamic control = kernel.Get(type);
            Assert.That(
                control is IThingControl<IThing>,
                Is.False);
        }
    }
}
于 2013-11-04T11:59:41.357 に答える
0

インターフェイスからそのドメイン オブジェクトへのジェネリック コントローラーを取得する場合は、設計を再検討します。

Ninject は、一般的なドメイン タイプをインターフェースとしてうまく処理できません。これは、ジェネリック型の不一致によるものです: Ninject - ジェネリック型の不一致を管理していますか?

于 2013-11-05T04:53:06.757 に答える