在《WCF技术剖析》中使用了Unity依赖注入容器,书中给出了两个使用Unity的方法:
方法一:直接在代码中使用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using System.Configuration; namespace UnityDemo { class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); container.RegisterType<IFoo,Foo1>("foo1"); container.RegisterType<IFoo,Foo2>("foo2"); Console.WriteLine(container.Resolve<IFoo>("foo1").GetType()); Console.WriteLine(container.Resolve<IFoo>("foo2").GetType()); Console.ReadKey(true); } } public interface IFoo { } public class Foo1 : IFoo { } public class Foo2 : IFoo { } }
输出结果为:
UnityDemo.Foo1
UnityDemo.Foo2
方法二:使用配置文件
1、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> <containers> <container> <types> <type name="foo1" type="UnityDemo.IFoo,UnityDemo" mapTo="UnityDemo.Foo1,UnityDemo"/> <type name="foo2" type="UnityDemo.IFoo,UnityDemo" mapTo="UnityDemo.Foo2,UnityDemo"/> </types> </container> </containers> </unity> </configuration>
2、代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using System.Configuration; namespace UnityDemo { class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); UnityConfigurationSection unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); unitySection.Containers.Default.Configure(container); Console.WriteLine(container.Resolve<IFoo>("foo1").GetType()); Console.WriteLine(container.Resolve<IFoo>("foo2").GetType()); Console.ReadKey(true); } } public interface IFoo { } public class Foo1 : IFoo { } public class Foo2 : IFoo { } }
输出与方法一相同。