Unity 2.0 HelloWord Example

Unity 是Microsoft的开源项目Enterprise Library的一个Ioc组件,与Mvc也有很好的集成,既可以通过代码来进行运行时依赖注入,也可以通过配置文件来进行设计时依赖注入,下面是一个使用配置文件的小例子。

配置文件App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" 
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity configSource="unity.config" />
</configuration>

外置的配置文件unity.config

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="HelloInterface.ISayHello,HelloInterface" mapTo="HelloWorld.MotherSayHello,HelloWorld"/>
    <register type="HelloInterface.ISayHello,HelloInterface" mapTo="HelloWorld.ChildSayHello,HelloWorld" name="child">
      <constructor>
        <param name="count" type="string" value="10" ></param>
      </constructor>
    </register>
  </container>
</unity>

unity结点中的xmlns 可以使用tellisense。

register结点中的type属性HelloInterface.ISayHello,HelloInterface前半部分是类全名(带名空间的类名),后半部分是程序集名称。

与 

<register type="HelloInterface.ISayHello,HelloInterface" mapTo="HelloWorld.MotherSayHello,HelloWorld"/>

对应的是

ISayHello say = container.Resolve<ISayHello>();

得到是say是MotherHello的实例。

项目架构

image

ISayHello.cs

    public interface ISayHello
    {
        void SayHello(string to);
    }

MotherSayHello.cs

    public class MotherSayHello : ISayHello
    {
       public void  SayHello(string to)
       {
 	        Console.WriteLine("Mother say hello to " + to);
       }
    }

ChildSayHello.cs

public class ChildSayHello : ISayHello
    {
        string count = "0";

        public ChildSayHello(string count)
        {
            this.count = count;
        }

        public void SayHello(string to)
        {

            Console.WriteLine("Child say " + count + " hello to " + to);
        }
    }

Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            /// 读取配置信息。
            var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            IUnityContainer container = new UnityContainer();
            section.Configure(container); // Unnamed <container> element

            //container.RegisterType<ISayHello, MotherSayHello>();
            /// 获取实例
            ISayHello say = container.Resolve<ISayHello>();
            ISayHello child = container.Resolve<ISayHello>("child");
            say.SayHello("you");
            child.SayHello("him");
        }
    }

输出结果

image

这样就能将MotherSayHello,ChildSayHello与客户程序解耦,客户程序只关心接口而不关心具体实现,而需要改变具体实现类时,不需要动客户代码,只需要修改配置文件,并开发相应的实现类即可。

Demo项目

原文地址:https://www.cnblogs.com/philzhou/p/2318527.html