====== リポジトリパターン ======
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Repo.Data;
using Repo.DAL;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RepoContext") ?? throw new InvalidOperationException("Connection string 'RepoContext' not found.")));
builder.Services.AddScoped(); //★IPespoインターフェースにMoivieRepoを挿入!
// Add services to the container.
builder.Services.AddControllersWithViews();
// ★Buildの前にサービスを登録する
var app = builder.Build();
・・・
↓おそらくProgram.csの
builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RepoContext") ?? throw new InvalidOperationException("Connection string 'RepoContext' not found.")));
によりコンテキストの接続文字列がGetConnectionString("RepoContext")になっている。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Repo.Models;
namespace Repo.Data
{
public class RepoContext : DbContext
{
public RepoContext (DbContextOptions options)
: base(options)
{
}
public DbSet Movie { get; set; } = default!;
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"RepoContext": "Server=(localdb)\\mssqllocaldb;Database=Repo.Data;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
using System.ComponentModel.DataAnnotations;
namespace Repo.Models
{
public class Movie
{
public int Id { get; set; }
public string? Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string? Genre { get; set; }
public decimal Price { get; set; }
}
}
using System;
using System.Collections.Generic;
using Repo.Models;
namespace Repo.DAL
{
public interface IRepo
{
IEnumerable GetMovies();
}
}
using Repo.Data;
using Repo.Models;
namespace Repo.DAL
{
public class MovieRepo : IRepo
{
private RepoContext _context;
public MovieRepo()
{
}
public MovieRepo(RepoContext context)
{
_context = context;
}
public IEnumerable GetMovies()
{
return _context.Movie.ToList();
}
}
}
↓おそらくProgram.csの
builder.Services.AddScoped();
によりコンストラクターの引数にはMovieRepo が渡されている。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Repo.Data;
using Repo.Models;
using Repo.DAL;
namespace Repo.Controllers
{
public class MoviesController : Controller
{
private IRepo _repo;
public MoviesController(IRepo repo) //★←DI
{
_repo = repo;
}
public IActionResult Index()
{
return View(_repo.GetMovies());
}
・・・