一个Unity例子

接口,与实现都在不同dll中,UnitySample项目只引用接口interfaces.dll

using Interfaces;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity.Configuration;

namespace UnitySample
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.LoadConfiguration("loggerContainer");
            ILogger logger = container.Resolve<ILogger>();
            logger.write("");
            Console.Read();
        }
    }
}

  接口:

namespace Interfaces
{
   public interface ILogger
    {
        void write(string log);
    }
}

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 xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container name="loggerContainer">
      <types>
        <type type="Interfaces.ILogger,Interfaces" mapTo="OneLoggerDll.OneLogger,OneLoggerDll" 
             />
      </types>

    </container>

  </unity>
</configuration>

第一个接口实现:oneLogger.dll

using System.Threading.Tasks;
using Interfaces;

namespace OneLoggerDll
{
    public class OneLogger:ILogger
    {
        public void write(string log)
        {
            Console.Write("onelogger!");
        }
    }
}

第二个接口实现:twoLogger.dll

using System.Text;
using System.Threading.Tasks;

namespace TwoLogger
{
    public class TwoLogger:ILogger
    {
        public void write(string log)
        {
            Console.Write("two logger!");
        }
    }
}

 注意点:LoadConfiguration是IUnityContainer的扩展函数,要引用这个dll,在Microsoft.Practices.Unity.Configuration.dll中的Microsoft.Practices.Unity.Configuration namespace下定义的UnityContainerExtensions。

 

posted on 2015-08-04 17:07  oyl  阅读(667)  评论(0编辑  收藏  举报

导航