首先要在项目中安装Unity,通过NuGet搜索Unity。
1.定义接口 IDependencyResolver
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOCContainer { public interface IDependencyResolver : IDisposable { /// <summary> /// 注册 T类型实例 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> void Register<T>(T instance); /// <summary> /// 注入 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="existing"></param> void Inject<T>(T existing); /// <summary> /// 解析 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <returns></returns> T Resolve<T>(Type type); T Resolve<T>(Type type, string name); T Resolve<T>(); T Resolve<T>( string name); IEnumerable<T> ResolveAll<T>(); } } |
2.具体实现接口 UnityDependencyResolver
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOCContainer { [Serializable] public class UnityDependencyResolver : IDisposable, IDependencyResolver { //注入容器 private IUnityContainer _container; public UnityDependencyResolver() : this ( new UnityContainer()) { UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection( "unity" ); _container.LoadConfiguration(configuration, "UnityContainer" ); } public UnityDependencyResolver(IUnityContainer container) { _container = container; } public void Register<T>(T instance) { //注册实例 _container.RegisterInstance(instance); } public void Inject<T>(T existing) { //注入加载 _container.BuildUp(existing); } public T Resolve<T>(Type type) { //解析 return (T)_container.Resolve(type); } public T Resolve<T>(Type type, string name) { return (T)_container.Resolve(type, name); } public T Resolve<T>() { return _container.Resolve<T>(); } public T Resolve<T>( string name) { return _container.Resolve<T>(name); } public IEnumerable<T> ResolveAll<T>() { //解析容器中所有 IEnumerable<T> namedInstances = _container.ResolveAll<T>(); T unnamedInstance = default (T); try { unnamedInstance = _container.Resolve<T>(); } catch (ResolutionFailedException) { //When default instance is missing } if (Equals(unnamedInstance, default (T))) { return namedInstances; } return new ReadOnlyCollection<T>( new List<T>(namedInstances) { unnamedInstance }); } public void Dispose() { if (_container != null ) { _container.Dispose(); } } } } |
3.定义工厂接口 IDependencyResolverFactory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using IOCContainer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOCContainer { public interface IDependencyResolverFactory { /// <summary> /// 创建IDependencyResolver的实例 /// </summary> /// <returns></returns> IDependencyResolver CreateInstance(); } } |
4.具体实现工厂接口 DependencyResolverFactory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using IOCContainer; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace IOCContainer { public class DependencyResolverFactory : IDependencyResolverFactory { private Type _resolverType; public DependencyResolverFactory( string resolverTypeName) { _resolverType = Type.GetType(resolverTypeName, true , true ); } public DependencyResolverFactory() { _resolverType = Type.GetType(ConfigurationManager.AppSettings[ "DependencyResolverTypeName" ], true , true ); } public IDependencyResolver CreateInstance() { //根据类型创建实例对象 return Activator.CreateInstance(_resolverType) as IDependencyResolver; } } } |
5.调用工厂封装 IoC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | using IOCContainer; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOCContainer { public static class IoC { //解析器 private static IDependencyResolver _resolver; /// <summary> /// 初始化,创建实例对象 /// </summary> /// <param name="factory"></param> [DebuggerStepThrough] public static void InitializeWith(IDependencyResolverFactory factory) { _resolver = factory.CreateInstance(); } /// <summary> /// 注册对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> [DebuggerStepThrough] public static void Register<T>(T instance) { _resolver.Register(instance); } /// <summary> /// 注入对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="existing"></param> [DebuggerStepThrough] public static void Inject<T>(T existing) { _resolver.Inject(existing); } /// <summary> /// 解析对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <returns></returns> [DebuggerStepThrough] public static T Resolve<T>(Type type) { return _resolver.Resolve<T>(type); } /// <summary> /// 解析对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="name"></param> /// <returns></returns> [DebuggerStepThrough] public static T Resolve<T>(Type type, string name) { return _resolver.Resolve<T>(type, name); } /// <summary> /// 解析对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> [DebuggerStepThrough] public static T Resolve<T>() { return _resolver.Resolve<T>(); } /// <summary> /// 解析对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> [DebuggerStepThrough] public static T Resolve<T>( string name) { return _resolver.Resolve<T>(name); } /// <summary> /// 解析对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> [DebuggerStepThrough] public static IEnumerable<T> ResolveAll<T>() { return _resolver.ResolveAll<T>(); } /// <summary> /// 销毁 /// </summary> [DebuggerStepThrough] public static void Reset() { if (_resolver != null ) { _resolver.Dispose(); } } } } |
6.配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http: //go.microsoft.com/fwlink/?LinkID=237468 --> <section name= "entityFramework" type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission= "false" /> <!--声明容器--> <section name= "unity" type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <!--定义类型别名--> <aliases> <add alias= "IProduct" type= "UnityTest.IProduct,UnityTest" /> <add alias= "Milk" type= "UnityTest.Milk,UnityTest" /> <add alias= "Sugar" type= "UnityTest.Sugar,UnityTest" /> </aliases> <!--容器--> <container name= "UnityContainer" > <!--映射关系--> <register type= "IProduct" mapTo= "Milk" name= "Milk" ></register> <register type= "IProduct" mapTo= "Sugar" name= "Sugar" ></register> </container> </unity> <connectionStrings> <add name= "DefaultConnection" connectionString= "Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-UnityTest-20160816022913.mdf;Initial Catalog=aspnet-UnityTest-20160816022913;Integrated Security=True" providerName= "System.Data.SqlClient" /> </connectionStrings> <appSettings> <add key= "webpages:Version" value= "3.0.0.0" /> <add key= "webpages:Enabled" value= "false" /> <add key= "ClientValidationEnabled" value= "true" /> <add key= "UnobtrusiveJavaScriptEnabled" value= "true" /> <!--Unity IOC容器--> <add key= "DependencyResolverTypeName" value= "IOCContainer.UnityDependencyResolver,IOCContainer" /> </appSettings> <!--省略了其他配置...--> </configuration> |
7.具体实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /// <summary> /// 商品 /// </summary> public interface IProduct { string ClassName { get ; set ; } string ShowInfo(); } /// <summary> /// 牛奶 /// </summary> public class Milk : IProduct { public string ClassName { get ; set ; } public string ShowInfo() { return "牛奶" ; } } /// <summary> /// 糖 /// </summary> public class Sugar : IProduct { public string ClassName { get ; set ; } public string ShowInfo() { return "糖" ; } } |
8.使用Ioc得到对象
1 2 3 4 5 6 7 8 9 | //初始化 指定注册器 IoC.InitializeWith( new DependencyResolverFactory( "IOCContainer.UnityDependencyResolver" )); //初始化 使用默认注册器,配置文件中配置,IOCContainer.UnityDependencyResolver 的无参构造函数 //IoC.InitializeWith(new DependencyResolverFactory()); //得到实例 IProduct sugar = IoC.Resolve<IProduct>( "Sugar" ); string result = sugar.ShowInfo(); Response.Write(result); |
来源:http://www.cnblogs.com/qqlin/archive/2012/10/18/2720830.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2015-09-06 WebAPI 抛出HttpResponseException异常