jQueryを使ってWCFのサービスにアクセス
Using jQuery to directly call ASP.NET AJAX page methodsで紹介されているようにPageMethodを使うのがとてもシンプルでいいと思うのですが、PageMethodはstaticメソッドじゃないといけないのでMEFで管理されたインスタンスを取得するの自分でルックアップしないといけないんですよね。それもひとつの手ですが、WCFを使えば前のエントリでつくったMefServiceBehaviorを使って依存性を解決できます。
サンプル
かんたんなサンプルで動作を確認してみました。
サービスコントラクト
Visual StudioのItemからAJAX-enabled WCF Serviceを追加します。そして、次のように記述します。前のエントリで作ったMefServiceBehaviorを追加しているのとプロパティでGreetingをImportしているのがポイント。
namespace WebApplication2
{
[MefServiceBehavior]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GreetingService
{
[Import]
public Greeting Greeting { get; set; }[OperationContract]
public string Hello()
{
return Greeting.Hello();
}
}
}
web.config
AJAX-enabled WCF Serviceを追加するとweb.configに自動で次のような記述が追加されます。
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication2.GreetingServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication2.GreetingService">
<endpoint address="" behaviorConfiguration="WebApplication2.GreetingServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication2.GreetingService" />
</service>
</services>
</system.serviceModel>
MEFでExportされるクラス
クラスにはExport属性をつけておきます。
namespace WebApplication2
{
[Export(typeof(Greeting))]
public class Greeting
{
public string Hello()
{
return "Hello!!!";
}
}
}
サーバー側は以上。
Default.aspx
aspxやhtmlではjQueryを使ってアクセスできます。
<div id="result">result</div>
<script type="text/javascript">
$(document).ready(function () {
$("#result").click(function () {
$.ajax({
type: "POST",
url: "GreetingService.svc/Hello",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#result").text(msg.d);
}
});
});
});
</script>
WCFから返されるmsgオブジェクトのdというプロパティが気になる場合はこちらに説明があります。
まとめ
- WCFに対してjQueryでアクセスできる。
- PageMethodを使う方法のほうがシンプルだが、WCFはMEFなどのDIコンテナと統合させやすいのがメリット。
- WebFormを使わない場合でもこの方法が利用できる。
WebFormやMVCなくてもjQueryとWCFでWebアプリつくれそう。でも、数が増えるとweb.configの設定が面倒くさそうな気がします。
追記
web.configに設定しない方法も提供されていました。
マークアップのコードを開いて以下の設定でためしたところOKでした(GreetingService2は上記のGreetingServiceのweb.configの設定がないバージョン)。
<%@ ServiceHost
Language="C#"
Debug="true"
Service="WebApplication2.GreetingService2"
CodeBehind="GreetingService2.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>