c# – Unity构造函数参数

前端之家收集整理的这篇文章主要介绍了c# – Unity构造函数参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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构造函数

解决方法

您可以使用ParameterOverride,如:
var p = container.Resolve<IPerson>(new ParameterOverride("EntityName",entityName));

这告诉unity使用名为“EntityName”的参数将entityName实例提供给构造函数.

您可以在这里找到一些额外的信息:http://msdn.microsoft.com/en-us/library/ff660920(v=pandp.20).aspx

原文链接:https://www.f2er.com/csharp/91918.html

猜你在找的C#相关文章