Blame view

web/WebApp/AutofacExt.cs 1.49 KB
赖素文 authored
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
// ***********************************************************************
// <summary>IOC扩展</summary>
// ***********************************************************************

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using WebRepository;
using IContainer = Autofac.IContainer;

namespace WebApp
{
    public static class AutofacExt
    {
        private static IContainer _container;
        public static IContainer InitAutofac(IServiceCollection services)
        {
            var builder = new ContainerBuilder();

            //services.AddScoped(typeof(IAuth), typeof(LocalAuth));

            //注册app
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());

            //缓存注入
            //services.AddScoped(typeof(ICacheContext), typeof(CacheContext));
            services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));

            //筛选器注入
            //services.AddScoped<OperLogFilter>();
            //services.AddScoped<InterfaceLogFilter>();

            builder.Populate(services);

            _container = builder.Build();
            return _container;
        }

        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }
    }
}