1

次のようなコンストラクターメソッドを持つ型を登録しようとしています:

public Foo (int myNumber, IBar bar) {...}

Unity コンテナー経由で IBar のインスタンスを生成します。Foo を登録して解決するにはどうすればよいですか?

以下の例に関して、 new Foo... の行をユニティレジスタに置き換えて方法を解決するにはどうすればよいですか?

public interface IBar
{

  public void SayNumber();

}

public class Bar : IBar
{
    public void SayNumber()
    {
        Coonsole.Write("Number : ");
    }
}


public interface IFoo
{
    void int GetMyNumberTimesTwo();
    public int MyNumber{get;}
    public IBar Bar {get;}
}

public class Foo : IFoo
{

    private IBar _bar;
    private readonly int _myNumber;

    public Foo (int myNumber, IBar bar)
    {
        _myNumber = myNumber;
        _bar = bar;
    }

    public void GetMyNumberTimesTwo() {return _myNumber * 2; }
    public IBar { get{ return _bar; } }
}


public static void Main(string[] args)
{

     var container = new UnityContainer();
     container.RegisterType<IBar, Bar>();

     // QUESTION: So how should I Register and Resolve the container to achive 
       //  the line below? 

      IFoo f = new Foo(999, container.ResolveType<IBar>()); // This should be replaced upon your answer

     Console.WriteLine(f.Bar.SatNumber + f.GetMyNumberTimesTwo());
}
4

1 に答える 1

3

タイプを次のように登録します。

container.RegisterType<IFoo, Foo>(new InjectionConstructor(999, typeof(IBar)));
于 2012-10-25T11:38:59.597 に答える