技术开发 频道

基于Provider的自定义服务

IT168技术文档

    在使用 Membership 的时候可以为同一种操作方法定义多种行为,而具体使用哪种行为只需要在 Web.Config 中定义即可。

    这样可以极大的促进了系统的灵活性,可是 Membership 这种 Provider 服务是怎么设计的呢?查了一些资料,也查看了 .Framework 2.0 的反编译源码,最终还是在 MSDN 上的一篇英文资料中找到了答案。

    设计这种模式,似乎并不是那么容易,需要设计许多类方可构建基于Provider的自定义服务。

    下面是一个基本Provider的自定义服务的示例,它公开了两个操作方法“RetrieveImage”和“SaveImage”。它有可以会使用不同的数据库,这样可以定义多种处理方法。只需要在 Web.Config 中进行配置,就可以让系统调用相应的行为来进行处理。
    1、 首先构建一个 ImageProvider 它继承了 ProviderBase 类。

ProviderBase
    2、 我们先定义一个使用 SQL Server 的处理方法。
SqlServer 处理方法
    配置基于Provider的自定义服务,现在可以看看如何在 Web.Config 中配置它所需的节点。这里在 <System.Web> 节中添加了 <ImageService> 节,在属性 defaultProvider 中指定了它使用的默认 Provider 服务。

    3. Web.Config 文件中配置 Image Service
<configuration > <connectionStrings> <add name="ImageServiceConnectionString" connectionString="" /> </connectionStrings> <system.web> <imageService defaultProvider="SqlImageProvider"> <providers> <add name="SqlImageProvider" type="SqlImageProvider" connectionStringName="ImageServiceConnectionString"/> </providers> </imageService> </system.web> </configuration>
    结构节点<ImageServer> 现在系统是不可识别的,所有必需还要有一个相应的类用来描述 <ImageServer> 配置节。

    4. <imageServer> 配置节的描述类
描述类
    这一下可以在 Web.Config 中注册 <imageService> 节了,并且它会被系统识别。

    5. 创建 <imageService> 这个配置节的处理类
<configuration > <configSections> <sectionGroup name="system.web"> <section name="imageService" type="ImageServiceSection, CustomSections" allowDefinition="MachineToApplication" restartOnExternalChanges="true" /> </sectionGroup> </configSections> <connectionStrings> <add name="ImageServiceConnectionString" connectionString="" /> </connectionStrings> <system.web> <imageService defaultProvider="SqlImageProvider"> <providers> <add name="SqlImageProvider" type="SqlImageProvider" connectionStringName="ImageServiceConnectionString"/> </providers> </imageService> </system.web> </configuration>
    现在可以加载并初始化自定义的 Providers 上面的事情都完成后,就可以实现这个 ImageService 了,它将根据 Web.Config 加载配置中默认的ImageProvider ,可以在 ImageService 类中直接使用它。

    6、创建 ImageService 类,它将使用配置中的实例来处理
ImageService类
    这些在 Asp.NET 2.0 中被支持。

0
相关文章