繁体   English   中英

我应该如何在Unity中注册这个具有参数化构造函数的类型?

[英]How should I register this type that has parameterized constructor, in Unity?

我试图注册一个具有构造函数方法的类型:

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

我通过Unity容器生成IBar实例。 我应该如何注册和解决Foo?

关于下面的例子,我如何用一个单位寄存器替换新的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());
}

将类型注册为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM