C# System.ComponentModel.Composition中的Export和Import特性标签的简单使用。

本文介绍了一个基于 .NET 的组件化开发框架 System.ComponentModel.Composition 的简单应用案例。通过 Export 和 Import 特性的结合使用,实现了组件之间的解耦和动态装配。此框架类似于依赖注入(IOC),方便在运行时替换组件。

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

微软给我们提供的强大的组件化开发框架:System.ComponentModel.Composition。我也是刚刚接触不久,下面我就班门弄斧,向大家展示下一个简单的demo。

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Go go = new Go();

            //获取当前执行的程序集中所有的标有特性标签的代码段
            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            //将所有Export特性标签存放进组件容器中(其实是一个数组里面)
            CompositionContainer container = new CompositionContainer(catalog);

            //找到所传入对象中所有拥有Import特性标签的属性,并在组件容器的数组中找到与这些属性匹配的Export特性标签所标注的类,然后进行实例化并给这些属性赋值。
            //简而言之,就是找到与Import对应的Export所标注的类,并用这个类的实例来给Import所标注的属性赋值,用于解耦。
            container.ComposeParts(go);

            if (go.test!=null)
            {
                go.test.show();
            }
            Console.ReadLine();
        }
    }

    //定义一个测试接口
    interface ITest {
        void show();

    }

    //Export出去的类型和名称都要和Import标注的属性匹配,类型可以写ITest, 也可以写Test
    [Export("wakaka",typeof(ITest))]
    class Test : ITest
    {
        public void show()
        {
            Console.WriteLine("OK");
        }
    }

    class Go
    {
        [Import("wakaka")]
        public ITest test { get; set; }
    }
}

代码执行效果截图:



其实这个东西类似于IOC,其实就是一个解耦的功能,我们如想使用其他人写的ITest的实现类,只需要更改下程序集就可以轻松做到,当然前提是其他人写的实现类上的Export特性标签的匹配信息要与我们Import的属性的信息匹配。

using FLC.Api.Bus; using FLC.Api.Bus.Import.Model; using FLC.Api.Bus.MEF; using FLC.Api.Model.MEF; using FLC.Common.AppLogCom; using FLC.Common.DataAccess; using FLC.Tools; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.ComponentModel.Composition; using ywx.bip.bus.Common; using ywx.bip.bus.Model.BIP; using ywx.bip.bus.Model.BIPVO; using ywx.bip.bus.Model.MESVO; using System.Linq; using System.Collections.Generic; using System.Data; using FLC.Api.Bus.Import; namespace ywx.bip.bus { /// <summary> /// 同步BIP物料 /// </summary> [Export(typeof(IBusInterface))] public class GetMaterial : IBusInterface { public override FLC.Api.Model.MEF.BusData<JObject, JArray> Do(AppDatabaseTrans trans, FLC.Api.Model.MEF.BusData<JObject, JArray> data) { var interfaceUrl = "/nccloud/api/uapbd/material/material/queryMaterial"; var input = new InputObject(); input.company_no = "99"; var sql = "select tt_lasttime from flc_timingtask where tt_name='同步物料档案'"; var sTime = AppDatabase.QuerySingle<DateTime>(sql); var strartTime = "2010-01-01 00:00:00"; if(sTime!=null) { strartTime = sTime.ToString("yyyy-MM-dd HH:mm:ss"); } input.edit_time = $"{strartTime}~{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"; var inputstr = JsonConvert.SerializeObject(input); AppLog.WriteLog($"同步物料接口收到参数inputstr:" + inputstr); var apicommon = ApiCommon.CreateInstance(); var client = apicommon.apiClient; client.Url = ywx.bip.bus.Common.Common.serverUrl + interfaceUrl; UFInterface uFInterface = new UFInterface(); uFInterface.ufinterface = new InputBase(); uFInterface.ufinterface.groupcode = "1"; uFInterface.ufinterface.pageInfo = new PageInfo(); uFInterface.ufinterface.pageInfo.pageIndex = "0"; uFInterface.ufinterface.pageInfo.pageSize = "10000"; uFInterface.ufinterface.data = new Data(); uFInterface.ufinterface.data.enablestate = "2"; if (!string.IsNullOrEmpty(input.data_no)) { string[] sname = new string[1]; sname[0] = input.data_no; uFInterface.ufinterface.data.code = sname; } else if (!string.IsNullOrEmpty(input.edit_time)) { //uFInterface.ufinterface.data.ts = inputobject.edit_time + "~" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); uFInterface.ufinterface.data.ts = input.edit_time; } string content = JsonConvert.SerializeObject(uFInterface); AppLog.WriteLog("GetMaterialData:query:" + content); client.Content = content; var result = client.AsyncRequest(); AppLog.WriteLog("GetMaterialData:result:" + result); ResultBIP<BIPMaterial> resultBIP = JsonConvert.DeserializeObject<ResultBIP<BIPMaterial>>(result); if (resultBIP.success || resultBIP.code == "1000000000") { if (resultBIP.data == null || resultBIP.data.Count == 0) throw new FLCException("没有满足条件的数据!"); } else if (!resultBIP.success && resultBIP.code == "1000000010" && resultBIP.message.Contains("失效") && resultBIP.message.Contains("token")) { ApiCommon.instance = null; Do(trans, data); } else throw new Exception(resultBIP.message); AppLog.WriteLog($"物料数量:{resultBIP.data.Count}"); // 2. 创建 ImportOtherModel 实例 var importOtherModel = new ImportOtherModel { Mapping = "ImportMaterial", Data = new List<DataSet>() }; var dataEntity = new List<DataEntry>(); foreach (var item in resultBIP.data) { var material = new Material { Name = item.name, Macode = item.code, Maccode = item.pk_marbasclass, FNumber = item.pk_material, Mastd = item.materialspec, GroupCode = item.pk_measdoc, IMassDate=item.qualitynum }; var de = new DataEntry(); de.Material = new List<Material>(); de.Material.Add(material); dataEntity.Add(de); } var root = new Root { Data = dataEntity,Mapping= "ImportMaterial" }; foreach (var entry in dataEntity) { DataSet dataSet = new DataSet(); // 动态生成 Productorder 的 DataTable DataTable productorderTable = ComFun.ConvertToDataTable(entry.Material); dataSet.Tables.Add(productorderTable); // 添加到 ImportOtherModel.Data 列表 importOtherModel.Data.Add(dataSet); } var importOtherBus = new ImportOtherBus(data.User, null); var importResult= importOtherBus.Save(importOtherModel); return data; } } }
06-08
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值