Prism6下的MEF:基于微软企业库的Cache
通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能。基于微软的企业库,我们的快速创建一个缓存的实现。
新建PrismSample.Infrastructure.Cache
新建一个类库项目,将其命名为PrismSample.Infrastructure.Cache,然后从nuget中下载微软企业库的Cache。

然后新建我们的CacheManager类:
using Microsoft.Practices.EnterpriseLibrary.Caching;
using System.ComponentModel.Composition;
namespace PrismSample.Infrastructure.Cache
{
[Export("PrismSampleCache", typeof(ICacheManager))]
public class CacheManager : ICacheManager
{
ICacheManager _cacheManager;
public CacheManager()
{
_cacheManager = CacheFactory.GetCacheManager("MemoryCacheManager");
}
public object this[string key]
{
get
{
return _cacheManager[key];
}
}
public int Count
{
get
{
return _cacheManager.Count;
}
}
public void Add(string key, object value)
{
_cacheManager.Add(key, value);
}
public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
{
_cacheManager.Add(key, value, scavengingPriority, refreshAction, expirations);
}
public bool Contains(string key)
{
return _cacheManager.Contains(key);
}
public void Flush()
{
_cacheManager.Flush();
}
public object GetData(string key)
{
return _cacheManager.GetData(key);
}
public void Remove(string key)
{
_cacheManager.Remove(key);
}
}
}
其中MemoryCacheManager是我们稍后需要在App.config文件中配置的。
修改生成后事件:
xcopy "$(TargetPath)" "$(SolutionDir)\PrismSample\bin\Debug\" /Y

之所以添加生成后事件,是因为Cache的类库的引入不是通过Project间的项目引用来实现的,是在运行时MEF的容器去寻找指令集,所以我们把程序集都放置到运行目录下。
修改App.config配置文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<cachingConfiguration defaultCacheManager="MemoryCacheManager">
<cacheManagers>
<add name="MemoryCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching" expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
<add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching"
name="NullBackingStore" />
</backingStores>
</cachingConfiguration>
</configuration>
配置文件的生成可以通过微软企业库的工具(配置方式)
修改Bootstrapper,将目录下符合条件的dll全部导入
using Prism.Mef;
using PrismSample.Infrastructure.Abstract.Presentation.Interface;
using System.ComponentModel.Composition.Hosting;
using System.Windows;
using Prism.Logging;
using PrismSample.Infrastructure.Logger;
using System.IO;
using System;
namespace PrismSample
{
public class Bootstrapper : MefBootstrapper
{
private const string SEARCH_PATTERN = "PrismSample.Infrastructure.*.dll";
protected override DependencyObject CreateShell()
{
IViewModel shellViewModel = this.Container.GetExportedValue<IViewModel>("ShellViewModel");
return shellViewModel.View as DependencyObject;
}
protected override void InitializeShell()
{
Application.Current.MainWindow = (Shell)this.Shell;
Application.Current.MainWindow.Show();
}
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
//加载自己
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(this.GetType().Assembly));
//加载当前目录
DirectoryInfo dirInfo = new DirectoryInfo(@".\");
foreach (FileInfo fileInfo in dirInfo.EnumerateFiles(SEARCH_PATTERN))
{
try
{
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(fileInfo.FullName));
}
catch (Exception ex)
{
this.Logger.Log( string.Format("导入异常:{0}", ex.Message), Category.Exception, Priority.None);
}
}
}
protected override ILoggerFacade CreateLogger()
{
return new Logger();
}
}
}
测试运行
修改ShellViewModel的构造函数
[ImportingConstructor]
public ShellViewModel([Import("ShellView", typeof(IView))]IView view,
[Import]ILoggerFacade logger,
[Import("PrismSampleCache", typeof(ICacheManager))] ICacheManager _cacheManager)
{
this.View = view;
this.View.DataContext = this;
_cacheManager.Add("SampleValue", "CacheValue");
this._text = _cacheManager.GetData("SampleValue").ToString();
logger.Log("ShellViewModel Created", Category.Info, Priority.None);
}
运行结果:

小结
本文用微软企业库实现了一个简单的缓存系统。
源码下载
参考信息
patterns & practices – Enterprise Library
黄聪:Microsoft Enterprise Library 5.0 系列教程(一) : Caching Application Block (初级)
Prism6下的MEF:基于微软企业库的Cache的更多相关文章
- 基于微软企业库的AOP组件(含源码)
软件开发,离不开对日志的操作.日志可以帮助我们查找和检测问题,比较传统的日志是在方法执行前或后,手动调用日志代码保存.但自从AOP出现后,我们就可以避免这种繁琐但又必须要实现的方式.本文是在微软企业库 ...
- 微软企业库的Cache
微软企业库的Cache 通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSamp ...
- 在数据库访问项目中使用微软企业库Enterprise Library,实现多种数据库的支持
在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreS ...
- [EntLib]微软企业库5.0 学习之路——第一步、基本入门
话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...
- 在开发框架中扩展微软企业库,支持使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库
在前面随笔<在代码生成工具Database2Sharp中使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库,实现免安装Oracle客户端,兼容3 ...
- 【公开课】《奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱》文字记录与反馈
本期分享的内容: <奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱> 时间:2016年11月02日 课程主讲人:叶锡文 从事商业智能行业,有丰富的实施经验,擅长 ...
- 微软企业库5.0 学习之路——第八步、使用Configuration Setting模块等多种方式分类管理企业库配置信息
在介绍完企业库几个常用模块后,我今天要对企业库的配置文件进行处理,缘由是我打开web.config想进行一些配置的时候发现web.config已经变的异常的臃肿(大量的企业库配置信息充斥其中),所以决 ...
- 微软企业库5.0 学习之路——第七步、Cryptographer加密模块简单分析、自定义加密接口及使用—下篇
在上一篇文章中, 我介绍了企业库Cryptographer模块的一些重要类,同时介绍了企业库Cryptographer模块为我们提供的扩展接口,今天我就要根据这些 接口来进行扩展开发,实现2个加密解密 ...
- 微软企业库5.0 学习之路——第六步、使用Validation模块进行服务器端数据验证
前端时间花了1个多星期的时间写了使用jQuery.Validate进行客户端验证,但是那仅仅是客户端的验证,在开发项目的过程中,客户端的信息永远是不可信的,所以我们还需要在服务器端进行服务器端的验证已 ...
随机推荐
- Nginx SSL TLS部署最佳实践
本文介绍nginx在提供HTTPS时使用的一些其他配置选项. 虽然这些功能有助于优化nginx的SSL和TLS,但这不是一个完整对加固nginx的介绍. 确保您的服务器安全的最佳方法是不仅需要正确的配 ...
- VS Code 快捷键使用小技巧
相关文档 官方文档(英文版):Documentation for Visual Studio Code 中文文档(未完成):GitHub - jeasonstudio/CN-VScode-Docs: ...
- C#的static
1.static意思是静态,可以修饰类.字段.属性.方法2.标记为static的就不用创建实例对象调用了,可以通过类名直接点出来3.static三种用法:4.用于变量前,表示每次重新使用该变量所在方法 ...
- Android 的窗口管理系统 (View, Canvas, WindowManager)
http://blog.csdn.net/ritterliu/article/details/39295271 From漫天尘沙 在图解Android - Zygote 和 System Server ...
- 检測iPhone/iPad设备方向的三种方法
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/iefreer/article/details/24210391 使用meta tag "v ...
- python下载脚本
#/usr/bin/env python#coding:UTF-8import timeimport os,sysimport urllib2 url = 'http://downloaduat.la ...
- XGBOOST应用及调参示例
该示例所用的数据可从该链接下载,提取码为3y90,数据说明可参考该网页.该示例的“模型调参”这一部分引用了这篇博客的步骤. 数据前处理 导入数据 import pandas as pd import ...
- [ZJOI2005]午餐
嘟嘟嘟 贪心+dp. 首先贪心很容易想到,把吃饭时间长的人排在前面.因为打饭时间的顺序对最终答案没有影响,所以可以以吃饭时间为关键字排序. 然后就是dp了(我当时还自信满满的贪心交了一发--显然WA啊 ...
- 使用HostAliases 添加pod 的/etc/hosts
默认的pod 的/etc/hosts 无法自动数据 [root@master1 ~]# kubectl exec smsservice-5c7ff5f74-bc969 -n testihospital ...
- go标准库的学习-encoding/json
参考https://studygolang.com/pkgdoc 导入方式: import "encoding/json" json包实现了json对象的编解码,参见RFC 462 ...