使用微软依赖注入器Microsoft.Extensions.DependencyInjection

这篇博客介绍了如何在单元测试和ASP.NET Core MVC应用中进行服务注册和依赖注入。首先展示了如何在静态BaseTest类中加载业务层和数据层的DLL文件,并使用反射注册接口及其实现到服务容器。然后,在测试用例中通过IServiceProvider获取并调用注册的服务。在ASP.NET Core MVC的控制器中,展示了如何通过构造函数注入来使用这些服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注册服务到容器

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WebNetCore5_Img_Storage.BLL;
using WebNetCore5_Img_Storage.DAL;
using WebNetCore5_Img_Storage.IBLL;
using WebNetCore5_Img_Storage.IDAL;

namespace XUnitTestProject1
{
    /// <summary>
    /// 初始化依赖注入
    /// </summary>
    public class BaseTest
    {
        /// <summary>
        /// 服务集合
        /// </summary>
        public readonly static IServiceCollection services = null;

        /// <summary>
        /// 服务提供
        /// </summary>
        public readonly static ServiceProvider  serviceProvider = null;

        static BaseTest()
        {
            services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            //servers.AddScoped<ILoginUserBLL, LoginUserBLLImpl>();
            //servers.AddScoped<IUserDAL, UserDALImpl>();

            try
            {
                //业务层注入  
                string path = AppDomain.CurrentDomain.BaseDirectory;
                Assembly bll_impl = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.BLL.dll");
                Assembly bll_interface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IBLL.dll");
                //Assembly bll_impl = Assembly.Load("WebNetCore5_Img_Storage.BLL");
                //Assembly bll_interface = Assembly.Load("WebNetCore5_Img_Storage.IBLL");
                var typesInterface = bll_interface.GetTypes();
                var typesImpl = bll_impl.GetTypes();
                foreach (var item in typesInterface)
                {
                    var name = item.Name.Substring(1);
                    string implBLLImpName = name + "Impl";
                    var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));
                    if (impl != null)
                    {
                        //services.AddTransient(item, impl);
                        //services.AddSingleton(item, impl);
                        services.AddScoped(item, impl);
                    }
                }

                //数据层注册
                //Assembly dalAssemblys = Assembly.Load("WebNetCore5_Img_Storage.DAL");
                //Assembly dalInterface = Assembly.Load("WebNetCore5_Img_Storage.IDAL");
                Assembly dalAssemblys = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.DAL.dll");
                Assembly dalInterface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IDAL.dll");
                var dalTypesImpl = dalAssemblys.GetTypes();
                var dalTypesInterface = dalInterface.GetTypes();
                foreach (var item in dalTypesInterface)
                {
                    var name = item.Name.Substring(1);
                    string implDalName = name + "Impl";
                    var impl = dalTypesImpl.FirstOrDefault(w => w.Name.Equals(implDalName));
                    if (impl != null)
                    {
                        //services.AddTransient(item, impl);
                        services.AddScoped(item, impl);
                    }
                }

                serviceProvider = services.BuildServiceProvider();
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }

    }
}

调用


using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
using System.Collections;
using System.Collections.Generic;

  //测试EF并发查询
        [Fact]
        public async Task Test5()
        {
		    //提取注册的服务接口
            ILoginUserBLL userbll = serviceProvider.GetService<ILoginUserBLL>();
            IImgCategoryBLL   categoryBLL  = serviceProvider.GetService<IImgCategoryBLL>();
            try
            {
               var list = await userbll.PageUserAsync(null, 1, 10);
               var page=await categoryBLL.PageImgCategoryAsync(null ,1,10);
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }        
        }

ASP.NET Core MVC调用参考,构造函数注入

using Microsoft.AspNetCore.Mvc;
using MvcSimplePager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebNetCore5_Img_Storage.Handler;
using WebNetCore5_Img_Storage.IBLL;
using WebNetCore5_Img_Storage.Model;

public class CategoryController : BaseController
    {
        private readonly IImgCategoryBLL imgCategoryBLL;
        private readonly IAtlasTagBLL atlasTagBLL;
        private readonly IImgBLL imgBLL;

        public CategoryController(IImgCategoryBLL _imgCategoryBLL, IAtlasTagBLL _atlasTagBLL, IImgBLL _imgBLL)
        {
            imgCategoryBLL = _imgCategoryBLL;
            atlasTagBLL = _atlasTagBLL;
            imgBLL = _imgBLL;
        }

        //view 图册列表
        public async Task<IActionResult> CategoryList(Img_category img_Category, int p = 1, int rows = 10)
        {
            //读取标签列表
            var pageTag = await atlasTagBLL.PageAtlas_tag(null, 1, 200);
            ViewBag.tagList = pageTag.List;
            return View();
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值