微软企业库的Cache

微软企业库的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 (初级)

时间: 2024-08-04 18:26:48

微软企业库的Cache的相关文章

分享一个大型进销存供应链项目(多层架构、分布式WCF多服务器部署、微软企业库架构)

分享一个大型进销存供应链项目(多层架构.分布式WCF多服务器部署.微软企业库架构) 这是一个比较大型的项目,准备开源了.支持N家门店同时操作.远程WCF+企业库5.0实现. 这块应该算是库存模块中的核心模块了,因为该块的业务逻辑比较多,比较繁琐,大致讲讲业务逻辑吧,大致的逻辑为:出库单/出库单-->填写订单-->出库/入库-->修改库存信息,按照这个顺序来完成入库出库,顺序不能颠倒,同时还要实现订单的删除,修改,在修改库存信息时由于表和表之间有很多的外键关系,所以要同时删除多张表中含有删

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

在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreSQL.IBM DB2.或者国产达梦数据库等等,这些数据库的共同特点是关系型数据库,基本上开发的模型都差不多,不过如果我们基于ADO.NET的基础上进行开发的话,那么各种数据库都有自己不同的数据库操作对象,微软企业库Enterprise Library是基于这些不同数据库的操作做的抽象模型,适合多数据

微软企业库5.0学习笔记(10)ASP.NET模块依赖注入

您可以使用HTTP模块,一个到ASP.NET HttpApplicationState类的扩展,在Global.asax编写代码强制ASP.NET在每一个页面请求时自动注入依赖的对象,就像在ASP.NET Web窗体应用程序中讨论的一样. 下列方法显示了一个合适的方法能够获取PreRequestHandlerExecute事件将它自己注入到ASP.NET的执行流水线,在每个页面请求中通过容器的BuildUp方法运行Http模块,并获取OnPageInitComplete事件.当OnPageIni

微软企业库5.0 支持 MySql

三步让 企业库支持 mysql 数据库 1.创建 MySqlDatabaseData 类 using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel; using Microsoft.Practices.EnterpriseLibrary.Data; using Mi

使用Microsoft EnterpriseLibrary(微软企业库)日志组件把系统日志写入数据库和xml文件

这里只是说明在项目中如何配置使用微软企业库的日志组件,对数据库方面的配置请参考其他资料. 1.在项目中添加Microsoft.Practices.EnterpriseLibrary.Data.dll.Microsoft.Practices.EnterpriseLibrary.Logging.dll.Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll这三个引用. 2.打开EnterpriseLibrary的配置工具EntLibCon

微软企业库研究之日志模块

很久之前研究微软的企业库时候写的,要注意需要引用Microsoft.Practices.EnterpriseLibrary.Logging组件库,因为ASP.NET5出来,微软在.netframework中自带了Logger,所以应该以后也不会用上. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.T

关于微软企业库配置注意事项

使用了微软企业库的应用程序配置文件配置注意事项, 一定要注意把configSections节点和connectionStrings节点放在最前面,并且一定要在appSettings节点之前,否则会报配置错误. <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSett

微软企业库5.0 调用 MySql 分页存储过程

1.需要完成两个前置条件后才可以使用 微软企业库5.0 调用 MySql 存储过程 微软企业库5.0 支持 MySql MySql 分页存储过程 2.需要添加一个继承 IParameterMapper 接口的类分配查询参数 using System.Data; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using Grass.Extend; namespace Grass.MySqlDa

微软企业库6 Data Access Application Block 扩展

虽然标题是对6的扩展,其实对于4.5同样适用,因为企业库在这几个版本中没太大变化 该扩展主要针对DataAccessor<T>,该类在创建时要传递几种接口:IParameterMapper,IRowMapper<T>,IResultSetMapper<T>,其中IRowMapper<T>企业库提供了MapBuilder<T>静态类来辅助创建相应的对应关系,但对于IParameterMapper和IResultSetMapper<T>没