我应该如何注册此活动,至今参数的构造函数,在Unity?(How should I register

2019-10-17 08:36发布

我想注册一个有一个构造方法就像一个类型:

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

我通过Unity容器生产伊巴尔的实例。 我应该如何值寄存器和解决富?

对于下面的例子,我怎能取代线新富......有统一注册和解析的方式?

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());
}

Answer 1:

注册类型

container.RegisterType<IFoo, Foo>(new InjectionConstructor(999, typeof(IBar)));


文章来源: How should I register this type that has parameterized constructor, in Unity?