net core 3.x使用Autofac以及使用Autofac进行自动注入

一、需要引入的库:

Autofac

Autofac.Extensions.DependencyInjection

 

二、Program.cs中添加:.UseServiceProviderFactory(new AutofacServiceProviderFactory())。如下:

  public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory());

 

三、StarpUp.cs中添加方法

 public void ConfigureContainer(ContainerBuilder builder)
        {
            //
        }

比如:

 public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule<AutomaticInjectionModule>();
        }
四、AutomaticInjectionModule的具体内容如下:
 /// <summary>
    /// 自动注入
    /// </summary>
    public class AutomaticInjectionModule : Module
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="moduleBuilder"></param>
        protected override void Load(ContainerBuilder moduleBuilder)
        {
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray();
            var perRequestType = typeof(IScoped);
            moduleBuilder.RegisterAssemblyTypes(assemblys)
                .Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType)
                .PropertiesAutowired()
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();

            var perDependencyType = typeof(ITransient);
            moduleBuilder.RegisterAssemblyTypes(assemblys)
                .Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType)
                .PropertiesAutowired()
                .AsImplementedInterfaces()
                .InstancePerDependency();

            var singleInstanceType = typeof(ISingleton);
            moduleBuilder.RegisterAssemblyTypes(assemblys)
                .Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType)
                .PropertiesAutowired()
                .AsImplementedInterfaces()
                .SingleInstance();
        }

    }

以上 ITransient、ISingleton、IScoped分别是代表三个生命周期的接口



posted @ 2020-05-23 18:10  向萧  阅读(679)  评论(0编辑  收藏  举报