依赖注入和控制反转/NetCore3.1使用Autofac

依赖注入和控制反转

https://blog.csdn.net/weixin_40867255/article/details/91049459

NetCore3.1使用Autofac

虽然netcore有内置容器,但是有一些功能不支持,所以使用Autofac。

首先Nuget安装Autofac

1.Program.cs修改

 

  1. startup.cs里增加方法

 

代码如下

 public void ConfigureContainer(ContainerBuilder builder)

        {

         

            var compilationLibrary = DependencyContext.Default

                .CompileLibraries

                .Where(x => !x.Serviceable

                && x.Type == "project")

                .ToList();

            var count1 = compilationLibrary.Count;

            List<Assembly> assemblyList = new List<Assembly>();

 

            foreach (var _compilation in compilationLibrary)

            {

                try

                {

                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));

                }

                catch (Exception ex)

                {

                    Console.WriteLine(_compilation.Name + ex.Message);

                }

            }

            builder.RegisterAssemblyTypes(assemblyList.ToArray())

             .AsSelf().AsImplementedInterfaces()

             .InstancePerLifetimeScope();

        }

posted @ 2020-08-12 15:12  康哥走荭  阅读(299)  评论(0编辑  收藏  举报