为了使用方便,对Autofac container的简单封装,记录如下,备以后用或分享给大家,欢迎讨论!
1 using Autofac; 2 using Autofac.Core.Lifetime; 3 using Autofac.Integration.Mvc; 4 5 public static class ContainerManager 6 { 7 private static IContainer _container; 8 9 public static void SetContainer(IContainer container) 10 { 11 _container = container; 12 } 13 14 public static IContainer Container 15 { 16 get { return _container; } 17 } 18 19 public static T Resolve<T>(string key = "", ILifetimeScope scope = null) where T : class 20 { 21 if (scope == null) 22 { 23 //no scope specified 24 scope = Scope(); 25 } 26 if (string.IsNullOrEmpty(key)) 27 { 28 return scope.Resolve<T>(); 29 } 30 return scope.ResolveKeyed<T>(key); 31 } 32 33 public static object Resolve(Type type, ILifetimeScope scope = null) 34 { 35 if (scope == null) 36 { 37 //no scope specified 38 scope = Scope(); 39 } 40 return scope.Resolve(type); 41 } 42 43 public static T[] ResolveAll<T>(string key = "", ILifetimeScope scope = null) 44 { 45 if (scope == null) 46 { 47 //no scope specified 48 scope = Scope(); 49 } 50 if (string.IsNullOrEmpty(key)) 51 { 52 return scope.Resolve<IEnumerable<T>>().ToArray(); 53 } 54 return scope.ResolveKeyed<IEnumerable<T>>(key).ToArray(); 55 } 56 57 public static T ResolveUnregistered<T>(ILifetimeScope scope = null) where T : class 58 { 59 return ResolveUnregistered(typeof(T), scope) as T; 60 } 61 62 public static object ResolveUnregistered(Type type, ILifetimeScope scope = null) 63 { 64 if (scope == null) 65 { 66 //no scope specified 67 scope = Scope(); 68 } 69 var constructors = type.GetConstructors(); 70 foreach (var constructor in constructors) 71 { 72 try 73 { 74 var parameters = constructor.GetParameters(); 75 var parameterInstances = new List<object>(); 76 foreach (var parameter in parameters) 77 { 78 var service = Resolve(parameter.ParameterType, scope); 79 if (service == null) throw new ArgumentException("Unkown dependency"); 80 parameterInstances.Add(service); 81 } 82 return Activator.CreateInstance(type, parameterInstances.ToArray()); 83 } 84 catch (ArgumentException) 85 { 86 87 } 88 } 89 throw new ArgumentException("在所有的依赖项中,未找到合适的构造函数。"); 90 } 91 92 public static bool TryResolve(Type serviceType, ILifetimeScope scope, out object instance) 93 { 94 if (scope == null) 95 { 96 //no scope specified 97 scope = Scope(); 98 } 99 return scope.TryResolve(serviceType, out instance); 100 } 101 102 public static bool IsRegistered(Type serviceType, ILifetimeScope scope = null) 103 { 104 if (scope == null) 105 { 106 //no scope specified 107 scope = Scope(); 108 } 109 return scope.IsRegistered(serviceType); 110 } 111 112 public static object ResolveOptional(Type serviceType, ILifetimeScope scope = null) 113 { 114 if (scope == null) 115 { 116 //no scope specified 117 scope = Scope(); 118 } 119 return scope.ResolveOptional(serviceType); 120 } 121 122 public static ILifetimeScope Scope() 123 { 124 try 125 { 126 if (HttpContext.Current != null) 127 return AutofacDependencyResolver.Current.RequestLifetimeScope; 128 129 //when such lifetime scope is returned, you should be sure that it‘ll be disposed once used (e.g. in schedule tasks) 130 return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); 131 } 132 catch (Exception) 133 { 134 //we can get an exception here if RequestLifetimeScope is already disposed 135 //for example, requested in or after "Application_EndRequest" handler 136 //but note that usually it should never happen 137 138 //when such lifetime scope is returned, you should be sure that it‘ll be disposed once used (e.g. in schedule tasks) 139 return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); 140 } 141 } 142 }
使用方法如下:
1 /// <summary> 2 /// IOCConfig 3 /// </summary> 4 public class IOCConfig 5 { 6 /// <summary> 7 /// RegisterAll 8 /// </summary> 9 public static void RegisterAll() 10 { 11 var iocBuilder = new Autofac.ContainerBuilder(); 12 13 //todo:为了能编译到web目录,并且发布方便,才在web项目中引用repository项目,在代码中不要直接使用之 14 iocBuilder.RegisterModule<RIS.Infrastructure.RegisterModule>(); 15 iocBuilder.RegisterModule<RIS.Biz.RegisterModule>(); 16 iocBuilder.RegisterModule<RIS.Repository.RegisterModule>(); 17 18 iocBuilder.Register((c, p) => new WebWorkContext(p.Named<string>("userToken"))) 19 .As<RIS.Biz.Core.IWorkContext>() 20 .InstancePerLifetimeScope(); 21 22 23 iocBuilder.RegisterControllers(Assembly.GetExecutingAssembly()); 24 25 iocBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 26 27 //iocBuilder.RegisterModelBinders(Assembly.GetExecutingAssembly()); 28 //iocBuilder.RegisterModelBinderProvider(); 29 //iocBuilder.RegisterModule<AutofacWebTypesModule>(); 30 var config = GlobalConfiguration.Configuration; 31 iocBuilder.RegisterWebApiFilterProvider(config); 32 IContainer iocContainer = iocBuilder.Build(); 33 config.DependencyResolver = new AutofacWebApiDependencyResolver(iocContainer); 34 System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(iocContainer)); 35 36 37 RIS.Biz.Core.ContainerManager.SetContainer(iocContainer); 38 } 39 } 40 41 // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明, 42 // 请访问 http://go.microsoft.com/?LinkId=9394801 43 /// <summary> 44 /// MvcApplication 45 /// </summary> 46 public class MvcApplication : System.Web.HttpApplication 47 { 48 /// <summary> 49 /// 程序启动入口 50 /// </summary> 51 protected void Application_Start() 52 { 53 IOCConfig.RegisterAll(); 54 55 AreaRegistration.RegisterAllAreas(); 56 57 WebApiConfig.Register(GlobalConfiguration.Configuration); 58 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 59 RouteConfig.RegisterRoutes(RouteTable.Routes); 60 BundleConfig.RegisterBundles(BundleTable.Bundles); 61 } 62 }
时间: 2024-10-29 01:12:50