月別アーカイブ: 2012年2月

【F# + ASP.NET MVC】 MEFによるDIを行うには

◆ DI用インターフェース

namespace PluginInterface

type IPlugin =
   abstract member Execute : string

◆ DI用オブジェクト(DLLファイル)

namespace PluginModule

open System
open System.ComponentModel.Composition
// DI用インターフェース
open PluginInterface

// Export属性でDI対象オブジェクトを設定
[<Export(typeof<IPlugin>)>]
type PluginModule1() =
    interface IPlugin with
        // インターフェース メソッド
        member this.Execute = "Hello Plugin!"

◆ Global.fs

namespace Sample.Routing

open System
open System.Web
open System.Web.Mvc
open System.Web.Routing
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open System.Reflection

open Sample.Mef
open Sample.Controllers

type Route = { controller : string
               action : string
               id : UrlParameter }

type Global() =
    inherit System.Web.HttpApplication() 

    static member RegisterRoutes(routes:RouteCollection) =
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
        routes.MapRoute("Default", 
                        "{controller}/{action}/{id}", 
                        { controller = "Home"; action = "Index"
                          id = UrlParameter.Optional } )

    member this.Start() =
        AreaRegistration.RegisterAllAreas() 
        Global.RegisterRoutes(RouteTable.Routes) |> ignore

        // カタログを登録
        let catalog = new AggregateCatalog()
        // 対象ディレクトリ内のファイルからカタログを取得
        catalog.Catalogs.Add(
            new DirectoryCatalog(base.Server.MapPath("Plugins"), "*.dll"))
        // アセンブリ内のカタログを取得
        catalog.Catalogs.Add(
            new AssemblyCatalog(Assembly.GetExecutingAssembly()))
        // コンテナを生成        
        let container = new CompositionContainer(catalog)
        container.ComposeParts(this)
        // Export属性のオブジェクトから依存情報を取得
        DependencyResolver.SetResolver(new MefDependencySolver(container))

        

◆ MEFのExport属性オブジェクトから依存情報を取得

namespace Sample.Mef

open System
open System.Collections.Generic
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open System.Web.Mvc

type MefDependencySolver(compositionContainer : CompositionContainer) as this =
    do this.CompositionContainer <- compositionContainer
        
    [<DefaultValue>]
    val mutable _compositionContainer : CompositionContainer
    
    member public this.CompositionContainer
        with get() = this._compositionContainer
        and set v = this._compositionContainer <- v

    interface IDependencyResolver with
        member this.GetService(serviceType : Type) : obj =
            let name = AttributedModelServices.GetContractName(serviceType)
            this.CompositionContainer.GetExportedValueOrDefault<obj>(name)

        member this.GetServices(serviceType : Type) : IEnumerable<obj> =
            this.CompositionContainer.GetExportedValues<obj>
                (serviceType.FullName)
    
    
    

◆ Controller

namespace Sample.Controllers

open System.Web
open System.Web.Mvc
open System.Web.SessionState
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open PluginInterface

[<Export>]
type HomeController() =
    inherit Controller()
    
    [<DefaultValue>]
    val mutable _plugin : IPlugin
    
    // Import属性でDI対象オブジェクトを設定
    [<Import>]
    member public x.Plugin
        with get() = x._plugin
        and set v = x._plugin <- v

    member this.Index() =
        // DIされたオブジェクトのメソッドを実行
        this.ViewData.["Message"] <- this.Plugin.Execute
        this.View() :> ActionResult

広告

【F# + ASP.NET MVC】 MEFによるプラグイン開発を行うには

◆ プラグイン用インターフェース

namespace PluginInterface

type IPlugin =
   abstract member Execute : string

◆ プラグイン(DLLファイル)

namespace PluginModule

open System
open System.ComponentModel.Composition
// プラグイン用インターフェース
open PluginInterface

// Export属性で、プラグイン用インターフェース型を設定
[<Export(typeof<IPlugin>)>]
type PluginModule1() =
    interface IPlugin with
        // インターフェース メソッド
        member this.Execute = "Hello Plugin!"

◆ MEFで動的にDLLファイルを読み込む

namespace Sample.Controllers

open System.Web
open System.Web.Mvc
open System.Web.SessionState
open System.ComponentModel.Composition
open System.ComponentModel.Composition.Hosting
open PluginInterface

type HomeController() =
    inherit Controller()
    
    [<DefaultValue>]
    val mutable plugin : IPlugin
    
    // Import属性で、プラグイン用インターフェース型を設定
    [<Import(typeof<IPlugin>)>]
    member public x.Plugin
        with get() = x.plugin
        and set v = x.plugin <- v

    member this.Index() =
        // binディレクトリよりカタログを検出(プラグイン用DLLをbinディレクトリに配置)
        let catalog =
            new DirectoryCatalog(HttpRuntime.BinDirectory, "PluginModule.dll")
        // カタログを用いてコンテナからパーツを検出
        let container = new CompositionContainer(catalog)
        this.Plugin <- container.GetExportedValue<IPlugin>()
        // プラグインのインターフェース メソッドを実行
        this.ViewData.["Message"] <- this.Plugin.Execute
        this.View() :> ActionResult

【F# + ASP.NET MVC】 ASPXビュー・エンジンを無効化するには

Global.fs

namespace Sample.Routing

open System
open System.Web
open System.Web.Mvc
open System.Web.Routing

type Route = { controller : string
               action : string
               id : UrlParameter }

type Global() =
    inherit System.Web.HttpApplication() 

    static member RegisterRoutes(routes:RouteCollection) =
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
        routes.MapRoute("Default", 
                        "{controller}/{action}/{id}", 
                        { controller = "Home"; action = "Index"
                          id = UrlParameter.Optional } )

    member this.Start() =
        // ASPXビュー・エンジンを無効化(わずかながらパフォーマンスが向上)
        ViewEngines.Engines.Clear()
        ViewEngines.Engines.Add(new RazorViewEngine())

        AreaRegistration.RegisterAllAreas() 
        Global.RegisterRoutes(RouteTable.Routes)

【F# + ASP.NET MVC】 リモート検証(指定されたアクションで正否を判定)を行うには

◆Controller(リモート検証用)
  ※ 検証のタイミングを遅らせる場合は、こちらを参照。

namespace Sample.Controllers

open System
open System.Web.Mvc

type LoginController() =
    inherit Controller()

    [<HttpPost>]
    member this.Index() =
        this.View() :> ActionResult

    // リモート検証アクション
    member this.IsLogin(userName : string) : JsonResult =
        if userName = "admin" then
            // 検証OK
            base.Json(true, JsonRequestBehavior.AllowGet)
        else
            // 検証NG
            base.Json(false, JsonRequestBehavior.AllowGet)

◆Entity

namespace Sample.Entities

open System.Web.Mvc

type Employee() =
    let mutable userName = ""
    
    // リモート検証
    [<Remote("IsLogin","Login")>]
    member x.UserName
        with get() = userName
        and set v = userName <- v
    

◆Controller

namespace Sample.Controllers

open System.Web
open System.Web.Mvc

open Sample.Models
open Sample.Entities

type HomeController() =
    inherit Controller()

    member this.Index() =
        this.View() :> ActionResult

    [<HttpPost>]
    member this.Index(entity:Employee) =
        // 検証結果を判定
        if this.ModelState.IsValid then
            this.ViewData.["Message"] <- "検証OK"
        else
            this.ViewData.["Message"] <- "検証NG"

        this.View(entity) :> ActionResult

◆View

@model Sample.Entities.Employee

@{ Layout = null; }

<!DOCTYPE html>
<html>
<head>
    <title>F# + ASP.NET</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
        type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
        type="text/javascript"></script>
    <!-- クライアントサイド検証を有効に設定-->
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
        type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
        type="text/javascript"></script>
</head>
<body>
    <div>
        @using (Html.BeginForm()) {
            @Html.ValidationSummary(true)
            <fieldset>
                <legend>User</legend>
                <div class="editor-label">
                    @Html.LabelFor(model => model.UserName)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.UserName)
                    @Html.ValidationMessageFor(model => model.UserName)
                </div>
                <p>
                    <input type="submit" value="Validate" />
                </p>
            </fieldset>
        }
    </div>
</body>
</html>

【F# + ASP.NET MVC】 アノテーション検証用Attributeを自作するには

◆Attribute(半角数値検証用)

namespace MsdnWeb.Attributes

open System
open System.ComponentModel.DataAnnotations
open System.Text.RegularExpressions

// 半角数値検証用Attribute
[<AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = false)>]
type NumberStringAttribute() =
    inherit ValidationAttribute()
        // コンストラクタ
        do
            base.ErrorMessage <- "{0}は半角数字を入力してください。"
        // 検証メソッド
        override x.IsValid(value, validationContext) =
            let regex = new Regex("^([0-9])*$")
            match value with
                // 値がブランクの場合は、検証OKとする
                | _ when value.ToString().Length = 0
                    -> ValidationResult.Success
                // 半角数値チェック
                | _ when regex.IsMatch(value.ToString())
                    -> ValidationResult.Success
                // 検証NG
                | _ -> ValidationResult(String.Empty)

◆Entity(使用例)

namespace MsdnWeb.Entities

open System.ComponentModel
open System.ComponentModel.DataAnnotations
open MsdnWeb.ValidationAttributes

type Employee() =
    let mutable age = ""
    
    // 半角数値検証
    [<NumberString>]
    member x.ID
        with get() = age
        and set v = age <- v

◆View

@model MsdnWeb.Entities.Employee

@{ Layout = null; }

<!DOCTYPE html>
<html>
<head>
    <title>F# + ASP.NET</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
        type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
        type="text/javascript"></script>
    <!-- クライアントサイド検証を有効に設定-->
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
        type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
        type="text/javascript"></script>
</head>
<body>
    <div>
        @using (Html.BeginForm()) {
            @Html.ValidationSummary(true)
            <fieldset>
                <legend>User</legend>
                <div class="editor-label">
                    @Html.LabelFor(model => model.ID)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.ID)
                    @Html.ValidationMessageFor(model => model.ID)
                </div>
                <p>
                    <input type="submit" value="Validate" />
                </p>
            </fieldset>
        }
    </div>
</body>
</html>

【F# + ASP.NET MVC】 複数のプロパティを参照して検証するには

◆Entity

namespace MsdnWeb.Entities

open System.ComponentModel
open System.ComponentModel.DataAnnotations

type Employee() =
    let mutable id = ""
    let mutable password = ""
    
    [<DisplayName("ID")>]
    member x.ID
        with get() = id
        and set v = id <- v

    [<DisplayName("パスワード")>]
    [<DataType(DataType.Password)>]
    member x.Password
        with get() = password
        and set v = password <- v

    // 複数のプロパティを参照しての検証
    interface IValidatableObject with
        member x.Validate(validationContext : ValidationContext)
            = seq { 
                if (x.ID = "admin") && (x.Password = "ok") then
                    ()
                else
                    yield ValidationResult(
                        "IDまたはパスワードが間違っています。"
                        , seq["ID"; "Password"] ) 
                }

◆View

@model MsdnWeb.Entities.Employee

@{ Layout = null; }

<!DOCTYPE html>
<html>
<head>
    <title>F# + ASP.NET MVC</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
        type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
        type="text/javascript"></script>
    <!-- クライアントサイド検証を有効に設定-->
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
        type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
        type="text/javascript"></script>
</head>
<body>
    <div>
        @using (Html.BeginForm()) {
            @Html.ValidationSummary(true)
            <fieldset>
                <legend>User</legend>
                <div class="editor-label">
                    @Html.LabelFor(model => model.ID)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.ID)
                    @Html.ValidationMessageFor(model => model.ID)
                </div>
                <div class="editor-label">
                    @Html.LabelFor(model => model.Password)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Password)
                    @Html.ValidationMessageFor(model => model.Password)
                </div>
                <p>
                    <input type="submit" value="Validate" />
                </p>
            </fieldset>
        }
    </div>
</body>
</html>