ASP.NET Core中使用Autofac

⒈添加相关依赖

Install-Package Autofac

⒉扫描项目接口实现类 

 1 using Autofac;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Reflection;
 5 using System.Text;
 6 
 7 namespace Unity_Test.Autofac
 8 {
 9     public class AutofacConfig
10     {
11         private static Lazy<IContainer> container = new Lazy<IContainer>(() =>
12         {
13             var containerBuilder = new ContainerBuilder();
14             RegisterTypes(containerBuilder);
15             var container = containerBuilder.Build();
16             return container;
17         });
18 
19         public static IContainer GetConfiguredContainer()
20         {
21             return container.Value;
22         }
23 
24         private static void RegisterTypes(ContainerBuilder containerBuilder)
25         {
26 
27             var dataAccess = Assembly.GetExecutingAssembly();
28 
29             containerBuilder.RegisterAssemblyTypes(dataAccess)
30                 .Where(w => w.Namespace.Contains("Unity_Test"))
31                 .AsImplementedInterfaces();
32         }
33     }
34 }

⒊代码中注入

 1 using Autofac;
 2 using Autofac.Core;
 3 using System;
 4 using Unity_Test.Autofac;
 5 
 6 namespace Unity_Test
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             IService service = AutofacConfig.GetConfiguredContainer().Resolve<IService>();
13             service.sayHello();
14             Console.ReadKey();
15         }
16     }
17 }

猜你喜欢

转载自www.cnblogs.com/fanqisoft/p/10516317.html