8
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
    }

How can I inject the firstName and lastName into Person constructor ?

2
  • Is there a reason you're doing all of the work in a single method? (instantiating a container, setting up bindings, etc) Commented Feb 7, 2013 at 18:56
  • 1
    You are right I should have moved it out of the method. I was testing out few things with Unity for the first time... Commented Feb 7, 2013 at 19:00

1 Answer 1

11

You can use a ParameterOverride like:

var p = container.Resolve<IPerson>(new ParameterOverride("EntityName", entityName));

This tells unity to supply the entityName instance to the constructor with the parameter named "EntityName".

You can find some additional info here: http://msdn.microsoft.com/en-us/library/ff660920(v=pandp.20).aspx

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.