微软IOC容器Unity简单代码示例2-配置文件方式

@(编程)

1. 通过Nuget下载Unity

这个就不介绍了

2. 接口代码


namespace UnityDemo
{
    interface ILogIn
    {
        void Login();
    }
}



namespace UnityDemo
{
    interface IUser
    {
        string GetUserName();
    }
}

3. 实现代码

using Microsoft.Practices.Unity;
using System;

namespace UnityDemo
{
    class LogInImpl : ILogIn
    {
        [Dependency]  
        public IUser userOper { get; set; }
        public void Login()
        {
            Console.WriteLine(this.userOper.GetUserName());
        }
    }
}




namespace UnityDemo
{
    class UserImpl:IUser
    {
        public string GetUserName()
        {
            return "keke";
        }
    }
}

4. 配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <containers>
      <container name="defaultContainer">
        <register type="UnityDemo.ILogIn,UnityDemo" mapTo="UnityDemo.LogInImpl,UnityDemo" />
        <register type="UnityDemo.IUser,UnityDemo" mapTo="UnityDemo.UserImpl,UnityDemo" />
      </container>
    </containers>
  </unity>
</configuration>

5. 调用代码

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Configuration;

namespace UnityDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName)
            as UnityConfigurationSection;
            configuration.Configure(container, "defaultContainer");
            var item = container.Resolve<ILogIn>();
            item.Login();
            Console.Read();
        }
    }
}


posted @ 2016-01-13 10:16  wardensky  阅读(267)  评论(0编辑  收藏  举报