.NET中 MEF应用于IOC

IOC解释

IOC,控制反转的意思。
所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B,反正A要用到B,则A依赖于B。所谓反转,你必须理解如果不反转,会怎么着,因为A必须要有B,才可以调用B,如果不反转,意思就是A主动获取B的实例:B b = new B(),这是获取获取B实例的方法,然后你就可以调用b对象了。      
所以,不反转,意味着A要主动获取B,才能使用B;到了这里,你就应该明白了反转的意思了。倒置就是A要调用B的话,A并不需要主动获取B,而是由其它人自动将B送上门来。
.net中可用的IOC容器非常多,如 CastleWindsor,Unity,Autofac,ObjectBuilder,StructureMap,Spring.Net等,这些第三方工具各不相同,但功能大体都相同,大都需要事先对接口与实现进行配对(通过代码或配置文件),然后由系统自动或手动来通过接口来获得相应实现类的实例,对象实例化的工作由IOC容器自动完成。

MEF优势

  1. 自VS2010 自带:MEF的功能在 System.ComponentModel.Composition.dll 程序集中,直接引用即可使用,不用安装第三方组件
  2. 配置:MEF是不需要使用配置文件或代码对接口与实现进行一一配对的,只需要简单的使用几个Attribute特性,就能自动完成源与目标的配对工作
  3. 自动化:系统初始化时自动遍历程序目录或指定文件夹下的dll,根据程序集中接口与类的特定Attribute特性进行自动配对。

在逻辑层中,使用 Export特性 标记与它匹配的接口;


在Conronl中,使用 Import 来给接口注入实现类的实例

IOC组件注册

1.MefDependencySolver实现代码如下:

   /// <summary>
    /// MEF依赖关系解析类
    /// </summary>
    public class MefDependencySolver : System.Web.Mvc.IDependencyResolver, System.Web.Http.Dependencies.IDependencyResolver
    {
        private readonly ComposablePartCatalog _catalog;
        private const string MefContainerKey = "MefContainerKey";

        public MefDependencySolver(ComposablePartCatalog catalog)
        {
            _catalog = catalog;
        }

        public IDependencyScope BeginScope()
        {
            return this;

        }
        public void Dispose()
        {

        }
        public CompositionContainer Container
        {
            get
            {
                if (!HttpContext.Current.Items.Contains(MefContainerKey))
                {
                    HttpContext.Current.Items.Add(MefContainerKey, new CompositionContainer(_catalog));
                }
                CompositionContainer container = (CompositionContainer)HttpContext.Current.Items[MefContainerKey];
                HttpContext.Current.Application["Container"] = container;
                return container;
            }
        }

        #region IDependencyResolver Members

        public object GetService(Type serviceType)
        {
            string contractName = AttributedModelServices.GetContractName(serviceType);
            return Container.GetExportedValueOrDefault<object>(contractName);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return Container.GetExportedValues<object>(serviceType.FullName);
        }

        #endregion
    }

2.Global中初始化MEF容器

       //设置MEF依赖注入容器
            DirectoryCatalog catalog = new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath);
            MefDependencySolver solver = new MefDependencySolver(catalog);
            //MVC依赖注入
            DependencyResolver.SetResolver(solver); 

源码:http://files.cnblogs.com/AntonWang/MEF%E5%BA%94%E7%94%A8%E4%BA%8EIOC.7z

转载于:https://www.cnblogs.com/AntonWang/p/3567431.html

Managed Extensibility Framework(MEF)是 .NET Framework 和 .NET Core 的一个插件化框架,可以帮助开发者实现可扩展的用程序。MEF 框架在 .NET Core 是自带的,不需要额外安装。 使用 MEF 框架实现插件化开发的步骤如下: 1. 创建插件接口 首先需要定义一个插件接口,该接口定义了插件的基本功能和方法。例如: ```csharp public interface IPlugin { string Name { get; } void Execute(); } ``` 2. 创建插件实现类 接着需要创建一个或多个实现插件接口的类。例如: ```csharp [Export(typeof(IPlugin))] public class Plugin1 : IPlugin { public string Name => "Plugin1"; public void Execute() { Console.WriteLine("Plugin1 executed."); } } [Export(typeof(IPlugin))] public class Plugin2 : IPlugin { public string Name => "Plugin2"; public void Execute() { Console.WriteLine("Plugin2 executed."); } } ``` 注意:实现类需要使用 `[Export]` 属性进行标记,表示该类是一个插件。 3. 创建主程序 创建主程序并使用 MEF 框架加载插件。例如: ```csharp class Program { static void Main(string[] args) { var catalog = new DirectoryCatalog("plugins"); // 插件目录 var container = new CompositionContainer(catalog); foreach (var plugin in container.GetExportedValues<IPlugin>()) { Console.WriteLine("Loaded plugin: " + plugin.Name); plugin.Execute(); } } } ``` 这段代码会从指定的插件目录加载所有插件,并执行 `Execute` 方法。 注意:需要在主程序添加对 `System.ComponentModel.Composition` 命名空间的引用,才能使用 MEF 相关的类。 这就是使用 MEF 框架实现插件化开发的基本步骤。在实际,可以根据具体的需求进行更加复杂的插件实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值