ASP.NET Coreの Razor Pages でDIコンテナを利用する場合の例はこちらの記事を参照してください。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DIContainer
{
public interface IMyService
{
public string Exec();
}
public class MyService : IMyService
{
public string Exec()
{
return "Hello! Blazor App DI Container World!";
}
}
}
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
</Found>
<NotFound>
<LayoutView>
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DIContainer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyService, MyService>();
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
@page
@namespace DIContainer.Pages
<!DOCTYPE html>
<html lang="ja">
<head>
</head>
<body>
<app>
@(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
</app>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
@page "/Screen"
@inherits ScreenModel
<h3>Index</h3>
<button @onclick="ButtonClick">Button1</button>
<p>@MessageText</p>
@code {
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace DIContainer.Pages
{
public class ScreenModel:ComponentBase
{
[Inject]
public IMyService mysevice { get; set; }
public string MessageText;
public void ButtonClick()
{
MessageText = mysevice.Exec();
}
}
}
(アプリケーションルートURL)/Screen
のURLにアクセスします。下図のページが表示されます。画面の[Button1]をクリックします。@code
セクションのコードからインジェクションしたオブジェクトを参照したいこともあります。@Inject
ディレクティブを記述します。@page "/ScreenLight"
@inject IMyService ms
<h3>ScreenLight</h3>
<button @onclick="Button2Click">Button2</button>
<p>@messageText</p>
@code {
string messageText;
void Button2Click()
{
messageText = ms.Exec();
}
}
ScreenLight.razor
は Screen.razor
と同じ動作をするページです。Screen.razorはモデルクラスが別ファイルで存在します。一方 ScreenLight.razor
はボタンクリック後のロジックもrazorファイル中に実装しています。そのため、razorファイル内に、MyServiceオブジェクトをインジェクトして参照する必要があります。@inject
ディレクティブによりオブジェクトをインジェクトしてrazorファイル中で参照できます。ms
がインスタンス化されたオブジェクトになります。@inject IMyService ms
ms.Exec()
の記述により、MyServiceクラスの Exec メソッドが呼び出され、文字列を返します。返された文字列を画面に表示します。 void Button2Click()
{
messageText = ms.Exec();
}
(アプリケーションルートURL)/ScreenLight
にWebブラウザでアクセスします。下図のページが表示されます。using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DIContainer
{
public interface IYourService
{
public string Exec();
}
public class YourService : IYourService
{
public string Exec()
{
return "DIコンテナの世界にようこそ。";
}
}
}
services.AddSingleton<IYourService, YourService>();
を追記し下記の通り変更します。 public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyService, MyService>();
services.AddSingleton<IYourService, YourService>();
services.AddRazorPages();
services.AddServerSideBlazor();
}
@page "/ScreenMulti"
により、(アプリケーションルートURL)/ScreenMulti
にアクセスした際にこの画面を表示します。@inject ディレクティブにより、IMyService, IYourService の2つのオブジェクトをインジェクトして参照できる状態にしています。ボタンクリック時の処理では、IMyServiceのExecメソッドと、IYourService のExecメソッドを呼び出し、2つの結果を結合して画面に表示しています。@page "/ScreenMulti"
@inject IMyService ms
@inject IYourService ys
<h3>ScreenMulti</h3>
<button @onclick="Button3Click">Button3</button>
<p>@messageText</p>
@code {
string messageText;
void Button3Click()
{
messageText = ms.Exec() +" : "+ ys.Exec();
}
}
(アプリケーションルートURL)/ScreenMulti
のURLにアクセスします。下図の画面が表示されます。using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace DIContainer
{
public interface IOurService
{
public string Exec();
}
public class OurService:IOurService
{
IWebHostEnvironment _env;
IMyService _ms;
IYourService _ys;
public OurService(IWebHostEnvironment env, IMyService ms, IYourService ys)
{
_env = env;
_ms = ms;
_ys = ys;
}
public string Exec()
{
return _ms.Exec() + " : " + _ys.Exec() + " : " + _env.ApplicationName;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DIContainer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyService, MyService>();
services.AddSingleton<IYourService, YourService>();
services.AddSingleton<IOurService, OurService>();
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
@page "/ScreenEnv"
により、アプリケーションルートURL下の ScreenEnv ディレクトリアクセス時に画面を表示します。画面内のボタンをクリックした際には、インジェクションにより参照される、OurServiceクラスの Exec()
メソッドを呼び出します。@page "/ScreenEnv"
@inject IOurService os
<h3>ScreenEnviroment</h3>
<button @onclick="Button3Click">Button3</button>
<p>@messageText</p>
@code {
string messageText;
void Button3Click()
{
messageText = os.Exec();
}
}
Exec()
メソッドが呼び出された時点で、WebHostEnvironmentクラスのApplicationName
, MyServiceクラスのExec()
メソッド, YourServiceクラスのExec()
メソッドを呼び出し、それぞれの戻り値の文字列を連結して画面に表示します。 public class OurService:IOurService
{
IWebHostEnvironment _env;
IMyService _ms;
IYourService _ys;
public OurService(IWebHostEnvironment env, IMyService ms, IYourService ys)
{
_env = env;
_ms = ms;
_ys = ys;
}
public string Exec()
{
return _ms.Exec() + " : " + _ys.Exec() + " : " + _env.ApplicationName;
}
}
(アプリケーションルートURL)/ScreenMulti
のURLにアクセスします。下図の画面が表示されます。@inject
ディレクティブやInjet属性、コンストラクタインジェクションで簡単に追加できます。