zoukankan      html  css  js  c++  java
  • C# Autofac 的 BeanFactory

    using Autofac;
    using Microsoft.Practices.ServiceLocation;
    
    namespace Core.Common
    {
        /// <summary>
        /// 获取被Autofac注入的实例BeanFactory
        /// </summary>
        public class BeanFactory
        {
            /// <summary>
            /// 获取Bean
            /// </summary>
            /// <typeparam name="T">获取的实例类型</typeparam>
            /// <returns>获取的实例</returns>
            public static T GetBean<T>()
            {
                try
                {
                    if (System.Web.HttpContext.Current != null)
                    {
                        ILifetimeScope scope = System.Web.HttpContext.Current.Items[typeof(ILifetimeScope)] as ILifetimeScope;
                        if (scope != null)
                        {
                            return scope.Resolve<T>();
                        }
                    }
                }
                catch
                {
                }
    
                return ServiceLocator.Current.GetInstance<T>();
            }
    
            /// <summary>
            /// 获取Bean
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
            public static object GetBean(System.Type type) 
            {
                try
                {
                    if (System.Web.HttpContext.Current != null)
                    {
                        ILifetimeScope scope = System.Web.HttpContext.Current.Items[typeof(ILifetimeScope)] as ILifetimeScope;
                        if (scope != null)
                        {
                            return scope.Resolve(type);
                        }
                    }
                }
                catch
                {
                }
    
                return ServiceLocator.Current.GetInstance (type) ;
            }
        }
    }
  • 相关阅读:
    【CF 359B】Permutation
    如何更新 DevC++ 的编译器
    【LG 2801】教主的魔法
    矩阵浅谈
    NOI 系列赛常见技术问题整理
    Treap 浅谈
    DP 优化浅谈
    友链
    【CF 708C】Centroids
    我跳过的坑
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/8022495.html
Copyright © 2011-2022 走看看