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

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# WPF通过反射及Ioc容器综合实例相关的知识,希望对你有一定的参考价值。

概述

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

具体实现

   -. ①首先在引导程序页面通过发射加载类库,并将视图注入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

以上是关于C# WPF通过反射及Ioc容器综合实例的主要内容,如果未能解决你的问题,请参考以下文章

Unity容器在asp.net mvc中的IOC应用及AOP应用

.net core反射练习-简易版IOC容器实现

IOC容器和注入方式

通过反射实现IOC功能

IoC/DI的理解

Java反射