2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Windows11】C# ASP.NET CoreでServiceクラスのDI注入の方法

Posted at

ASP.NET CoreではModel - View - Controllerクラスが用意されています。
しかし、Serviceクラスのようなロジッククラスは用意されていませんので、自身でクラスを用意する必要があります。
その際に、Program.csに登録を忘れてしまうとアプリが起動できません。
なので、DI注入の方法について記載しておきます。

ディレクトリ構成

今回の記事で、DI注入するServiceクラスはプロジェクトルート配下に配置しています。

└── Project/
    ├── bin
    ├── Controllers/
    │   └── HomeController.cs
    ├── Models/
    │   └── AdminUserViewModel.cs
    ├── Service/
    │   └── PasswordHash.cs
    ├── Views/
    │   └── Home/
    │       ├── Index.cshtml
    │       └── Privacy.cshtml
    └── wwwroot

Program.csにServiceクラスを登録

ServiceクラスProgram.csに追加していきましょう。

注入した箇所は下記になります。

Program.cs
using ASPNETSQLServer.Service;
// ~(略)~
builder.Services.AddSingleton<PasswordHash>();

全体のProgram.csのコードは下記となります。

Program.cs
using ASPNETSQLServer.Service;
using Microsoft.AspNetCore.Identity; // PasswordHash サービスのnamespace

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddSingleton<PasswordHash>();//追加

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Serviceクラスになにを書いたのか?

今回は、パスワードのハッシュ化をServiceクラスに記載しました。

パッケージは下記を使っています。

PasswordHash.cs
using System;
using System.Security.Cryptography;
using System.Text;

namespace ASPNETSQLServer.Service;

public class PasswordHash
{
    public string HashPassword(string password)
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }

}

サイト

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?