Prism6下的MEF:基於微軟企業庫的Cache


通常,應用程序可以將那些頻繁訪問的數據,以及那些需要大量處理時間來創建的數據存儲在內存中,從而提高性能。基於微軟的企業庫,我們的快速創建一個緩存的實現。

新建PrismSample.Infrastructure.Cache

新建一個類庫項目,將其命名為PrismSample.Infrastructure.Cache,然后從nuget中下載微軟企業庫的Cache。
Image

然后新建我們的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

Image

之所以添加生成后事件,是因為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);
}

運行結果:
Image

小結

本文用微軟企業庫實現了一個簡單的緩存系統。
源碼下載

參考信息

patterns & practices – Enterprise Library
黃聰:Microsoft Enterprise Library 5.0 系列教程(一) : Caching Application Block (初級)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM