通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能。基于微软的企业库,我们的快速创建一个缓存的实现。

新建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的更多相关文章

  1. 基于微软企业库的AOP组件(含源码)

    软件开发,离不开对日志的操作.日志可以帮助我们查找和检测问题,比较传统的日志是在方法执行前或后,手动调用日志代码保存.但自从AOP出现后,我们就可以避免这种繁琐但又必须要实现的方式.本文是在微软企业库 ...

  2. 微软企业库的Cache

    微软企业库的Cache 通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSamp ...

  3. 在数据库访问项目中使用微软企业库Enterprise Library,实现多种数据库的支持

    在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreS ...

  4. [EntLib]微软企业库5.0 学习之路——第一步、基本入门

    话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...

  5. 在开发框架中扩展微软企业库,支持使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库

    在前面随笔<在代码生成工具Database2Sharp中使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库,实现免安装Oracle客户端,兼容3 ...

  6. 【公开课】《奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱》文字记录与反馈

        本期分享的内容: <奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱> 时间:2016年11月02日 课程主讲人:叶锡文 从事商业智能行业,有丰富的实施经验,擅长 ...

  7. 微软企业库5.0 学习之路——第八步、使用Configuration Setting模块等多种方式分类管理企业库配置信息

    在介绍完企业库几个常用模块后,我今天要对企业库的配置文件进行处理,缘由是我打开web.config想进行一些配置的时候发现web.config已经变的异常的臃肿(大量的企业库配置信息充斥其中),所以决 ...

  8. 微软企业库5.0 学习之路——第七步、Cryptographer加密模块简单分析、自定义加密接口及使用—下篇

    在上一篇文章中, 我介绍了企业库Cryptographer模块的一些重要类,同时介绍了企业库Cryptographer模块为我们提供的扩展接口,今天我就要根据这些 接口来进行扩展开发,实现2个加密解密 ...

  9. 微软企业库5.0 学习之路——第六步、使用Validation模块进行服务器端数据验证

    前端时间花了1个多星期的时间写了使用jQuery.Validate进行客户端验证,但是那仅仅是客户端的验证,在开发项目的过程中,客户端的信息永远是不可信的,所以我们还需要在服务器端进行服务器端的验证已 ...

随机推荐

  1. C# Repeater、webdiyer:AspNetPager分页 AspNetPager分页样式

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/vaecnfeilong/article/details/32712611 AspNetPager分页 ...

  2. 快速对Mysql添加索引的五个方法

    1.添加PRIMARY KEY(主键索引) mysql>ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` ) 2.添加UNIQUE(唯一索引 ...

  3. Mysql数据库的加密与解密

    数据加密.解密在安全领域非常重要.对程序员而言,在数据库中以密文方式存储用户密码对入侵者剽窃用户隐私意义重大. 有多种前端加密算法可用于数据加密.解密,下面我向您推荐一种简单的数据库级别的数据加密.解 ...

  4. 单例模式和JDBC

    配置文件: driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/blog user=root user=1234 properti ...

  5. Spring与SpringMVC的区别

    Spring是IOC和AOP的容器框架,SpringMVC是基于Spring功能之上添加的Web框架,想用SpringMVC必须先依赖Spring. 简单点的话可以将SpringMVC类比于Strut ...

  6. IDEA中使用vim删除复制代码的行号

    从别的地方复制来的源代码有时候会把前面的行号也一起拷过来,如果只是十几行代码的话手工去除还是方便的,但是如果代码有很多行的话,一行一行地删就不明智了. 例如我要复制以下代码 1 public clas ...

  7. Zephyr的Shell

    1 前言 通过Shell可以跟子系统打交道,子系统也可以提供很多接口供外部设置和读取信息. 下面就Shell的Kconfig配置.Shell的使用以及如何新建一个Shell命令展开. 可以说Shell ...

  8. u-boot全面分析

    uboot主Makefile分析1 uboot住Makefile分析参考:https://www.2cto.com/kf/201607/522424.html uboot version确定(Make ...

  9. Codechef TAPAIR Counting the important pairs 随机化、树上差分

    传送门 题意:给出一个$N$个点.$M$条边的无向连通图,求有多少组无序数对$(i,j)$满足:割掉第$i$条边与第$j$条边之后,图变为不连通.$N \leq 10^5 , M \leq 3 \ti ...

  10. 将WinForm程序(含多个非托管Dll)合并成一个exe的方法

    原文:将WinForm程序(含多个非托管Dll)合并成一个exe的方法 开发程序的时候经常会引用一些第三方的DLL,然后编译生成的exe文件就不能脱离这些DLL独立运行了. ILMerge能把托管dl ...