• .net core 2.0 Autofac


    参考自 https://github.com/VictorTzeng/Zxw.Framework.NetCore
    安装Autofac,在`project.csproj`加入
    <PackageReference Include="Autofac.Configuration" Version="4.0.1" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.2" />
    在`Startup.cs`中创建一个`public IContainer ApplicationContainer { get; private set; }`对象,并把`ConfigureServices`返回类型改为`IServiceProvider`
    上下文是用内置IOC创建,**将void的返回值改为`IServiceProvide`**
    控制器不能从容器中解析出来; 只是控制器构造函数参数。这意味着控制器生命周期,属性注入和其他事情不由Autofac管理 - 它们由ASP.NET Core管理。可以通过指定AddControllersAsServices()何时向服务集合注册MVC 来更改此设置`services.AddMvc().AddControllersAsServices();`。可以在填充服务之后覆盖控制器注册
    `InstancePerRequest`由`InstancePerLifetimeScope`替代
     public IContainer ApplicationContainer { get; private set; }
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddSession(a => 
                    {
                        a.IdleTimeout = TimeSpan.FromMinutes(20);
                        a.Cookie.HttpOnly = true;
                    });
                services.AddDistributedRedisCache(o => o.Configuration = Configuration.GetConnectionString("Redis"));
                //Add controllers as services so they'll be resolved.
                services.AddMvc().AddControllersAsServices().AddJsonOptions(options => {
                    //忽略循环引用
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    //不使用驼峰样式的key
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    //设置时间格式
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
                });        
                return InitIoC(services);
            }

    在Startup.cs添加方法

    /// <summary>
            /// IoC初始化
            /// </summary>
            /// <param name="services"></param>
            /// <returns></returns>
            private IServiceProvider InitIoC(IServiceCollection services)
            {
                IocContainer.Register(Configuration);//注册配置
                IocContainer.Register(typeof(BlogContext));//注册EF上下文
                IocContainer.Register(Assembly.GetExecutingAssembly());//注册controller
                return IocContainer.Build(services);
            }

    IocContainer自定义类

    /// <summary>
        /// Autofac Ioc容器
        /// </summary>
        public class IocContainer
        {
            private static ContainerBuilder _builder = new ContainerBuilder();
            private static IContainer _container;
            private static string[] _otherAssembly;
            private static List<Type> _types = new List<Type>();
            private static Assembly _assName;
    
            private static Dictionary<Type, Type> _dicTypes = new Dictionary<Type, Type>();
    
            /// <summary>
            /// 注册程序集
            /// </summary>
            /// <param name="assemblies">程序集名称的集合</param>
            public static void Register(params string[] assemblies)
            {
                _otherAssembly = assemblies;
            }
    
            /// <summary>
            /// 注册类型
            /// </summary>
            /// <param name="types"></param>
            public static void Register(params Type[] types)
            {
                _types.AddRange(types.ToList());
            }
            /// <summary>
            /// 注册程序集。
            /// </summary>
            /// <param name="implementationAssemblyName"></param>
            /// <param name="interfaceAssemblyName"></param>
            public static void Register(string implementationAssemblyName, string interfaceAssemblyName)
            {
                var implementationAssembly = Assembly.Load(implementationAssemblyName);
                var interfaceAssembly = Assembly.Load(interfaceAssemblyName);
                var implementationTypes =
                    implementationAssembly.DefinedTypes.Where(t =>
                        t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.IsNested);
                foreach (var type in implementationTypes)
                {
                    var interfaceTypeName = interfaceAssemblyName + ".I" + type.Name;
                    var interfaceType = interfaceAssembly.GetType(interfaceTypeName);
                    if (interfaceType.IsAssignableFrom(type))
                    {
                        _dicTypes.Add(interfaceType, type);
                    }
                }
            }
            /// <summary>
            /// 注册dal、controller
            /// </summary>
            /// <param name="ass"></param>
            public static void Register(Assembly ass){
                _assName = ass;
            }
            /// <summary>
            /// 注册
            /// </summary>
            /// <typeparam name="TInterface"></typeparam>
            /// <typeparam name="TImplementation"></typeparam>
            public static void Register<TInterface, TImplementation>() where TImplementation : TInterface
            {
                _dicTypes.Add(typeof(TInterface), typeof(TImplementation));
            }
    
            /// <summary>
            /// 注册一个实体
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="instance"></param>
            public static void Register<T>(T instance) where T:class
            {
                _builder.RegisterInstance(instance).SingleInstance();
            }
    
            /// <summary>
            /// 构建IOC容器,需在各种Register后调用。
            /// </summary>
            public static IServiceProvider Build(IServiceCollection services)
            {
                if (_otherAssembly != null)
                {
                    foreach (var item in _otherAssembly)
                    {
                        _builder.RegisterAssemblyTypes(Assembly.Load(item));
                    }
                }
    
                if (_types != null)
                {
                    foreach (var type in _types)
                    {
                        _builder.RegisterType(type).InstancePerLifetimeScope();
                    }
                }
    
                if (_dicTypes != null)
                {
                    foreach (var dicType in _dicTypes)
                    {
                        _builder.RegisterType(dicType.Value).As(dicType.Key);
                    }
                }
                _builder.Populate(services);
                //you can override the controller registration after populating services.
                if(_assName!=null){
                    _builder.RegisterAssemblyTypes(_assName).Where(t => t.Name.ToLower().EndsWith("dal")).PropertiesAutowired().InstancePerLifetimeScope();
                    _builder.RegisterAssemblyTypes(_assName).Where(t => t.Name.ToLower().EndsWith("controller")).PropertiesAutowired().InstancePerLifetimeScope();
                }
                _container = _builder.Build();
                return new AutofacServiceProvider(_container);
            }
    
            /// <summary>
            /// Resolve an instance of the default requested type from the container
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <returns></returns>
            public static T Resolve<T>()
            {
                return _container.Resolve<T>();
            }
        }
  • 相关阅读:
    32ES6 Map的介绍和API
    30ES6 集合介绍与API
    27ES6 Promise.prototype..then方法
    26ES6 Promise封装AJAX请求
    31ES6 集合实践
    221JavaSE 类和对象
    linux centos timer_create接口
    centos7 进入安全模式
    Python: Abstract Factory Pattern
    Python: Composite Pattern
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/9176410.html
Copyright © 2020-2023  润新知