zoukankan      html  css  js  c++  java
  • 微软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();
            }
        }
    }
    
    
    
  • 相关阅读:
    8.驱动与硬件通信
    11.ok6410之led驱动程序编写
    10.字符设备控制学习
    9.应用程序如何访问驱动
    linux内核打印数据到串口控制台,printk数据不打印问题
    nginx配置-location
    spring-cloud config配置中心
    idea中git stash--解决pull冲突或切换分支问题
    idea中git回退本地仓库版本
    idea中git回退远程仓库版本
  • 原文地址:https://www.cnblogs.com/wardensky/p/5126405.html
Copyright © 2011-2022 走看看