C# WPF通过反射及Ioc容器综合实例

概述

    这节主要通过发射+Caliburn.Micro自带的ioc容器实现加载并显示其它项目中的界面.实现效果如下: 

e4ecd66bdfa06d74f68f8e90fc80b86f.gif

具体实现

   -. ①首先在引导程序页面通过发射加载类库,并将视图注入ioc容器,这里为了实现解耦合注入了ICommonBasePage接口类型:

private void ExternalLoad()
        {
            //container = new SimpleContainer();
            //container.Instance(container);


            var asmPath = Assembly.GetAssembly(typeof(HelloBootstrapper)).Location;
            var path = Directory.GetParent(asmPath).FullName;
            string filePath = Path.Combine(path, "PluginTest.dll");


            //var assembly = Assembly.GetAssembly(typeof(PageBase));
            //container.AllTypesOf<ShellViewModel>(assembly);
            var assembly = Assembly.LoadFile(filePath);
            assembly.GetTypes()
                    .Where(type => type.IsClass)
                    .Where(type => type.Name.EndsWith("ViewModel"))
                    .ToList()
                     .ForEach(viewModelType => container.RegisterPerRequest(
                       typeof(ICommonBasePage), viewModelType.ToString(), viewModelType));


            //container
            //    .Singleton<IWindowManager, WindowManager>()
            //    .Singleton<IEventAggregator, EventAggregator>()
            //    .PerRequest<MainWindowViewModel>();
        }

接口定义在单独的类库中:

public interface ICommonBasePage
    {
        void ShowNewWindow();
    }

加入程序集到IEnumerable<Assembly>

protected override IEnumerable<Assembly> SelectAssemblies()
        {
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "PluginTest.dll");


            var assembly = Assembly.LoadFile(filePath);
            return new[] { Assembly.GetExecutingAssembly(), assembly };
        }

-.②PluginTest是要加载显示的项目:

PluginTestViewModel.cs源码如下:

using CommonShareBase;
using System.ComponentModel.Composition;
using System.Windows;


namespace PluginTest
{
    //[PluggablePart(name: "PluginTestViewModel", desciption: "This is PluginTestViewModel content pluggable part.", displayNameResourceKey: "PluginTestViewModel")]
    //[Export("PluginTestViewModel", typeof(IPluggablePart))]
    //[PartCreationPolicy(CreationPolicy.Shared)]
    ///也可以这样
    [Export(typeof(ICommonBasePage))]
    public class PluginTestViewModel : ICommonBasePage
    {
        //public void PreparePart(IPluggablePartContext pluggablePartContext)
        //{
        //    //throw new NotImplementedException();
        //}


        public void ShowNewWindow()
        {
            MessageBox.Show("dotnet讲堂");
        }
    }
}

PluginTestView.xaml代码如下:

<UserControl x:Class="PluginTest.PluginTestView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:PluginTest"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />


        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button Name="ShowNewWindow" Content="ShowNewWindow" Grid.Row="0" Grid.Column="0"  FontSize="35" Background="LightBlue"/>
    </Grid>
</UserControl>

-. ③在调用的地方先定义ICommonBasePage 类型的VM:

public ICommonBasePage PluginTestViewModel { get; set; }

按钮事件里面从ioc获取视图并给界面赋值:

public void IocTest4()
        {
            //通过接口实现解耦合
            var shellVM = IoC.Get<ICommonBasePage>();
            //shellVM.ShowNewWindow();


            PluginTestViewModel = shellVM;
            ActivateItemAsync(PluginTestViewModel);
        }

源码下载

链接:https://pan.baidu.com/s/1wtNduWVUiFV46WwWE4hrEw

提取码:6666

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中使用IoC容器可以让代码更加灵活、可扩展和易于维护。常见的IoC容器有Autofac、Unity、StructureMap等。 下面以Autofac为例,介绍如何在WPF中进行IoC容器注册。 1. 安装Autofac NuGet包 在Visual Studio中打开NuGet包管理器控制台,执行以下命令: ``` Install-Package Autofac ``` 2. 创建一个IoC容器 在App.xaml.cs文件中创建一个静态的Autofac容器: ```csharp public partial class App : Application { public static IContainer Container { get; private set; } protected override void OnStartup(StartupEventArgs e) { // 创建一个IoC容器 var builder = new ContainerBuilder(); // 注册依赖关系 builder.RegisterType<MyService>().As<IMyService>(); // 构建容器 Container = builder.Build(); base.OnStartup(e); } } ``` 在这个例子中,我们注册了一个名为MyService的服务,并将其标记为IMyService接口的实现类型。 3. 在应用程序中使用IoC容器 在需要使用服务的地方,我们可以使用容器解析服务的实例。 ```csharp public partial class MainWindow : Window { private readonly IMyService _myService; public MainWindow() { InitializeComponent(); // 通过IoC容器获取MyService的实例 _myService = App.Container.Resolve<IMyService>(); } } ``` 在这个例子中,我们使用IoC容器解析MyService的实例,并将其保存在_myService字段中。这样,在MainWindow类中就可以使用_myService字段调用MyService中的方法了。 通过这种方式,我们可以实现依赖注入,减少代码的耦合性,提高应用程序的可扩展性和易于维护性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值