Unity构造函数参数 [英] Unity constructor parameters

查看:68
本文介绍了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构造函数中?

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

推荐答案

您可以使用ParameterOverride,例如:

You can use a ParameterOverride like:

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

这告诉统一向构造函数提供 entityName 实例,并为其提供名为"EntityName"的参数.

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

您可以在此处找到一些其他信息: http://msdn.microsoft.com/zh-CN/library/ff660920(v = pandp.20).aspx

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

这篇关于Unity构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆