程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Autofac Container 的簡單的封裝重構,autofaccontainer

Autofac Container 的簡單的封裝重構,autofaccontainer

編輯:C#入門知識

Autofac Container 的簡單的封裝重構,autofaccontainer


為了使用方便,對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     }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved