在Winform/WPF中用反射快速实现依赖注入

using Kx.Mvvm.ViewModel;
using Kx.Service.Entry;
using Kx.Service.Service.Impl;
using Kx.View;
using Kx.View.ViewWindow;
using Kx.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;

namespace Kx
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            Services = ConfigureServices();
        }

        private IServiceProvider ConfigureServices()
        {
            ServiceCollection services = new ServiceCollection();

            services.AddScoped<SqlSugarServices>();
            services.AddScoped<SqlSugarHelper>();
            services.AddScoped<MyS7Entry>();
            services.AddScoped<ActualData>();

            #region Impl

            // 获取主项目的程序集
            var mainAssembly = Assembly.GetExecutingAssembly();

            // 获取引用的项目的程序集
            //IEnumerable<Assembly> referencedAssemblies = mainAssembly.GetReferencedAssemblies()
            //    .Where(a => a.Name.StartsWith("Kx.Service"))
            //    .Select(a => Assembly.Load(a));

            //引用.netFramework项目
            var assembly = mainAssembly.GetReferencedAssemblies()
                .Where(a => a.Name.StartsWith("Kx.Service"))
                .Select(a => Assembly.Load(a))
                .FirstOrDefault();

            //引用.netCore项目
            //var assembly = AppDomain.CurrentDomain.GetAssemblies()
            //.Where(a => a.FullName.StartsWith("Kx.Service"))
            //.FirstOrDefault();

            //结尾是Service的接口,例如AService
            var serviceTypes = assembly.GetTypes()
                .Where(t => t.IsInterface && t.Name.EndsWith("Service"));

            //结尾是ServiceImpl的类,例如AServiceImpl
            var implementationTypes = assembly.GetTypes()
                .Where(t => t.Name.EndsWith("ServiceImpl"));

            //遍历IAService接口
            foreach (var serviceType in serviceTypes)
            {
                //Linq查询结尾是ServiceImpl的类
                //例如AServiceImpl,比较它去掉Impl,首字母加上I,判断它是否和接口名IAService相等
                var implementationType = implementationTypes.FirstOrDefault(t =>
                    serviceType.Name == "I" + t.Name.Replace("Impl", ""));



                if (implementationType != null)
                {
                    //Console.WriteLine(serviceType.ToString());
                    //Console.WriteLine(implementationType.ToString());
                    services.AddScoped(serviceType, implementationType);
                }
            }
            #endregion


            //ViewModel
            #region ViewModel
            var viewModelTypes = Assembly.GetExecutingAssembly().GetTypes()
                .Where(t => t.Name.EndsWith("ViewModel"));

            foreach (var type in viewModelTypes)
            {
                services.AddScoped(type);
            }
            #endregion

            //services.AddScoped<MainViewModel>();
            services.AddScoped<MainView>();

            //services.AddScoped<Index1ViewModel>();
            services.AddScoped<IndexView1>();

            //services.AddScoped<AddIndex2WindowViewModel>();

            //services.AddScoped<Index2ViewModel>();
            services.AddScoped<IndexView2>() ;

            //services.AddScoped<Index3ViewModel>();
            //services.AddTransient<AddIndex2WindowView>(sp => new AddIndex2WindowView()
            //{
            //    DataContext = sp.GetService<AddIndex2WindowViewModel>()
            //}) ;


            services.AddScoped<IndexView3>();

            services.AddScoped<MyMainViewModel>();
            services.AddScoped<MyMainView>();
            
            return services.BuildServiceProvider();
        }

        public IServiceProvider Services { get; }
        public new static App Current => (App)Application.Current;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            //MainView mainView = this.Services.GetService<MainView>();
            //mainView.DataContext = this.Services.GetService<MainViewModel>();
            //mainView.Show();

            var mainView = this.Services.GetService<MyMainView>();
            mainView.DataContext = this.Services.GetService<MyMainViewModel>();
            mainView.Show();

            //Task.Run(async () =>
            //{
            //    while (true)
            //    {
            //        await Task.Delay(1000);
            //        await Console.Out.WriteLineAsync(Services.GetService<MyS7Entry>().MyShort1.ToString());
            //    }
            //});
        }
    }


}

利用反射快速将Impl,Service,ViewModel注入到IOC容器

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

潘诺西亚的火山

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

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

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

打赏作者

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

抵扣说明:

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

余额充值