2012-10-25 27 views
1

我想註冊一個具有類似構造方法的類型:我應該如何在Unity中註冊具有參數化構造函數的這種類型?

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

我通過Unity容器生產伊巴爾的實例。 我應該如何值寄存器和解決富?

關於下面的例子,我該如何用一個統一的寄存器替換新的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()); 
} 

回答

3

註冊類型

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

我沒有這樣,我不知道是有區別的,但:container.RegisterType (新InjectionConstructor(999,新ResolvedParameter ()) ); – pencilCake

+0

它們確實是等價的,提供的類型是一條捷徑。當你想解析一個特定的名字時,你確實需要使用ResolvedParameter,但是當你不需要一個名字時,你可以使用任何一個。 – fsimonazzi

相關問題