首页 > 代码库 > 验证Unity依赖注入的对象是否为同一个实例

验证Unity依赖注入的对象是否为同一个实例

在使用Unity的时候,能够很好的解耦,解除层与层之间的依赖性。这里有一个问题,每次向Unity中要对象实例的时候,这时候给出的是同一个吗?还是每次都是new一个新的?我来写代码验证一下。怎么验证两个对象是否为同一个呢,看这个对象在内存中的地址就行了,通过Hash码查看就可以。

namespace UnityApplication
{
    public interface IService
    {
        string Show();
    }
}


namespace UnityApplication
{
    public class Service : IService
    {
        public Service()
        {
            Console.WriteLine("<<<<<<<<<<<<<<");
        }

        public string Show()
        {
            return "Hello";
        }
    }
}


namespace UnityApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = CreateUnityContainerExe();
            IService service = container.Resolve<IService>();
            string result = service.Show();
            Console.WriteLine("''''''''''" + result + "llllllll" + service.GetHashCode());
            IService service2 = container.Resolve<IService>();
            Console.WriteLine("lllllllllll" + service2.GetHashCode());
            Console.ReadLine();
        }

        public static IUnityContainer CreateUnityContainerExe()
        {

            return CreateUnityContainer(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
        }  

        private static IUnityContainer CreateUnityContainer(Configuration configuration)
        {
            
                return InitializeContainer(configuration);
            }  

        private static IUnityContainer InitializeContainer(Configuration configuration)
        {
            var result = new UnityContainer();

            foreach (var section in configuration.Sections)
            {
                var unityConfigurationSection = section as UnityConfigurationSection;
                if (unityConfigurationSection != null)
                {
                    result.LoadConfiguration(unityConfigurationSection);
                }
            }

            return result;
        }  
    }
}

需要在配置文件中,配置相应的类与映射关系

<?xml version="1.0"?>
<configuration>

  <configSections>

    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>

  </configSections>

  <unity>
    <container>
      <register type="UnityApplication.IService, UnityApplication" mapTo="UnityApplication.Service, UnityApplication">
      </register>
    </container>
  </unity>
  
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
</configuration>

最终运行的时候,你会发现控制台输出的哈希地址根本就是不一样的,说明不是同一个实例,对象的地址根本不同,每次都会new一个新的。