2013-02-07 71 views
3
class Entity:IEntityName 
{ 
    #region IEntityName Members 

    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    #endregion 
} 

public class Person:IPerson 
{ 
    public IEntityName EntityName; 

    public Person() 
    { 
    } 

    public Person(IEntityName EntityName) 
    { 
     this.EntityName = EntityName; 
    } 

    public string ReverseName() 
    { 
     return string.Format("Your reverse name is {0} {1}",EntityName.LastName, EntityName.FirstName); 
    } 

    public override string ToString() 
    { 
     return string.Format("Name is {0} {1}", EntityName.FirstName, EntityName.LastName); 
    } 
} 

// Main Method 

private static string DisplayReverseName(string fName,string lName) 
{ 
     IUnityContainer container = new UnityContainer(); 
     container.RegisterType<IPerson, Person>().RegisterType<IEntityName,Entity>(); 

     IEntityName entityName = container.Resolve<IEntityName>(); 

     entityName.FirstName = fName; 
     entityName.LastName = lName; 
     var p = container.Resolve<IPerson>(); 
     return p.ReverseName(); // firstName and lastName are still null 
    } 

如何將firstName和lastName注入到Person構造函數中?Unity的構造函數參數

+0

有你做所有的工作在一個單一的方法的原因是什麼? (實例化一個容器,設置綁定等) –

+0

你說得對,我應該把它移出該方法。我第一次使用Unity測試了幾件事... – Learner

回答