The. NETCORE test unit uses Autofac dependency injection

Time:2021-12-7

1. Create a test project using xUnit test project, create a dependencyinjection folder, and add Di in it_ Test.cs file

public class DI_Test
    {
        public IContainer DICollections()
        {// get project path
            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
       //Log          
            ILoggerFactory loggerFactory = new LoggerFactory();
            IServiceCollection services = new ServiceCollection();

            //Read configuration file
            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile($"{basePath}appsettings.json", false, true).Build();
            services.AddSingleton(configuration);
            //Inject NLog log
            services.AddLogging(builder=> 
            {
                builder.AddConfiguration(configuration.GetSection("Logging")).AddNLog("NLog.config").AddDebug().AddConsole();
            });
            //Add to entity
            GlobalContext.Configuration = configuration;
            //Get configuration entity
            GlobalContext.AppSettings = configuration.GetSection("Appsettings").Get();
			//Add exception filter
            services.AddControllers(options =>
            {
                options.Filters.Add();// Global exception filter
            }).AddControllersAsServices();
			
            //Inject redis
            CacheStorageFactory.InitCacheStorage(new RedisCacheStorageProvider(GlobalContext.AppSettings.RedisServerString));
			//Injection database
            services.AddTransient(o => new ActiveTransactionProvider(GlobalContext.AppSettings.DbConnetion));



            //Instantiate the Autofac container and use reflection to get all classes that implement interfaces and inject them into the di container
            var container = new ContainerBuilder();
            container.RegisterModule();
            container.Populate(services);
            //Create a new container using the registered component
            var ApplicationContainer = container.Build();
            return ApplicationContainer;
        }
    }`

2. Add a service test file and call the method class using Autofac

public class AddressServiceTest
    {
        private readonly IAddressService  addressService;    // Commodity classification interface

        public AddressServiceTest()
        {
            var conllections = new DI_Test().DICollections();
            addressService = conllections.Resolve();
        }

        /// 
        ///Get address list
        /// 
        [fact (displayName = "get address list")]
        public async void GetProductCategory()
        {
            var response = await addressService.PageList(new Models.RequestModels.AddressPageListRequest { UserId= 86,MerchantId=47 });
            Assert.NotNull(response);
        }
    }

Note: the framework.ioc.autofacmodule class is the implementation class of user-defined Autofac injection. Readers can inject according to their own code. This article is for reference only and does not provide specific implementation code.