.net core获取已经注册的服务,调用它的方法

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using WebInfoFormReport.Model;

namespace WebInfoFormReport
{
    public class Startup
    {
        public static ServiceProvider Provider = null;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
          
            //数据层接口自动匹配
            string path = AppDomain.CurrentDomain.BaseDirectory;
            Assembly dalAssemblys = Assembly.LoadFrom(path + "WebInfoFormReport.DataImpl.dll");
            Assembly dalInterface = Assembly.LoadFrom(path + "WebInfoFormReport.IData.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.AddSingleton(item, impl);
                }
            }

            //业务层接口自动匹配
            Assembly bll_impl = Assembly.LoadFrom(path + "WebInfoFormReport.BusinessImpl.dll");
            Assembly bll_interface = Assembly.LoadFrom(path + "WebInfoFormReport.IBusiness.dll");
            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.AddSingleton(item, impl);
                }
            }
 
            Provider = services.BuildServiceProvider();
			
			//其他类里面调用已经注册的接口类
            var imgBusiness = Provider.GetService<IBusiness.IImgBusiness>();
 
        }
 
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王焜棟琦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值