zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    2.25家庭记账本小软件
    2.10简单体温记录小软件总结
    4.26PHP
    4.25Android
    4.24css
    4.23css
    4.22电梯演讲
    4.21python
    4.20python
    4.19python
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/10516317.html
Copyright © 2011-2022 走看看