質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Q&A

解決済

3回答

2040閲覧

DrylocにDbContextを設定したい。

退会済みユーザー

退会済みユーザー

総合スコア0

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

3グッド

1クリップ

投稿2021/03/23 03:47

編集2021/04/09 08:45

前提・実現したいこと

DrylocにDbContextを設定したいです、ASP.NET Core MVCはデフォルトのコンテナを利用しましたが、
WPFアプリ(.NET 5)の場合はなかったので、Drylocを使用したいですが、ネットで調べてもやり方がわかりませんでした。

C#

1// App.xaml.cs 2 3protected override void RegisterTypes(IContainerRegistry containerRegistry) { 4 // appsettings.jsonから接続文字列を取得 5 IConfiguration configuration = new ConfigurationBuilder() 6 .SetBasePath(Directory.GetCurrentDirectory()) 7 .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) 8 .Build(); 9 10 string connectionString = configuration.GetConnectionString("DbConnection"); 11 12 // コンテナのインスタンスを取得する(Dryloc) 13 IContainer container = containerRegistry.GetContainer(); 14 15 // TestDbContext ※Drylocの場合のやり方がわからない。 16 // container.Register<TestDbContext>(ifAlreadyRegistered: IfAlreadyRegistered.AppendNotKeyed); 17 18 /* 19 ASP.NET Core MVC(.NET 5)の場合 20 services.AddDbContext<TestDbContext>(options => { 21 options.UseLazyLoadingProxies(); 22 options.UseSqlServer(Configuration.GetConnectionString("DbConnection")) 23 }; 24 */ 25}

C#

1public class TestDbContext : DbContext { 2 public TestDbContext(DbContextOptions<AddDbContext> options) : base(options) { 3 4 } 5}

(追記)
Microsoft.Extensions.DependencyInjectionにてDbContextを使用する場合。

C#

1// Microsoft.Extensions.DependencyInjection の場合 2IConfiguration configuration = new ConfigurationBuilder() 3 .SetBasePath(Directory.GetCurrentDirectory()) 4 .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) 5 .Build(); 6 7IServiceCollection services = new ServiceCollection(); 8services.AddDbContext<TestDbContext>(options => { 9 options.UseLazyLoadingProxies(); 10 options.UseSqlServer(configuration.GetConnectionString("DbConnection")); 11});

ただし、WPFで使用しているPrismフレームワークがDrylocを使用していて、上記のMicrosoft.Extensions.DependencyInjectionが使えないため、Dryloc(またはUnity)が使えればよいのですが。

どなたかご教授お願いします。

(追記 修正) ※元のコードは間違いのため削除しました。
BluOxyさんの回答を元に実際のコードを記載しました。

C#

1// ITestDbContext 2 3using Microsoft.EntityFrameworkCore; 4using System.Threading; 5using System.Threading.Tasks; 6 7namespace DomainModel { 8 public interface ITestDbContext { 9 // インターフェースのプロパティ・メソッドを使うわけではなさそうなので、 10 // DbContextに追加したメソッドは全て定義しなければいけないのかは不明 11 12 // public Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()); 13 14 // DbSet<Department> Departments { get; set; } 15 } 16}

C#

1// TestDbContext 2 3using Microsoft.EntityFrameworkCore; 4using System; 5using System.Collections.Generic; 6using System.ComponentModel.DataAnnotations; 7using System.Diagnostics; 8using System.Linq; 9using System.Threading; 10using System.Threading.Tasks; 11 12namespace DomainModel { 13 public class TestDbContext : DbContext, ITestDbContext { 14 15 public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { 16 17 } 18 19 public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { 20 // ... 21 } 22 23 /// <summary> 24 /// Override OnModelCreating 25 /// </summary> 26 /// <param name="modelBuilder"></param> 27 protected override void OnModelCreating(ModelBuilder modelBuilder) { 28 // ... 29 30 base.OnModelCreating(modelBuilder); 31 } 32 33 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 34 string connectionString = "Data Source=..."; 35 36 optionsBuilder.UseSqlServer(connectionString); 37 optionsBuilder.UseLazyLoadingProxies(); 38 39 base.OnConfiguring(optionsBuilder); 40 } 41 42 // Test用の適当なクラス 43 public DbSet<Department> Departments { get; set; } 44 } 45}

C#

1// App.xaml 2 3using DomainModel; 4using DryIoc; 5using Microsoft.Extensions.Configuration; 6using Prism.DryIoc; 7using Prism.Ioc; 8using System.IO; 9using System.Windows; 10using UserInterface.Views; 11 12namespace UserInterface { 13 /// <summary> 14 /// Interaction logic for App.xaml 15 /// </summary> 16 public partial class App { 17 protected override Window CreateShell() { 18 return Container.Resolve<MainWindow>(); 19 } 20 21 protected override void RegisterTypes(IContainerRegistry containerRegistry) { 22 // appsettings.jsonはDbContextのDomainModelレイヤーに用意して読み込ませるかも 23 // (または依存関係が逆転しない他の方法) 24 // IConfiguration configuration = new ConfigurationBuilder() 25 // .SetBasePath(Directory.GetCurrentDirectory()) 26 // .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) 27 // .Build(); 28 29 // Drylocを利用する場合 30 var container = containerRegistry.GetContainer(); 31 container.Register<ITestDbContext, TestDbContext>(); 32 } 33 } 34}

appsettings.jsonはDbContextのDomainModelレイヤーに用意して読み込ませることを検討しようと思います。
(または依存関係が逆転しない他の方法)

DbContextインターフェースには、DbContextに追加したメソッドは全て定義しなければいけないのかはまだ不明ですが。

また、下記のPMのコマンドが使えなくなってしまいました。プロジェクト(レイヤー)の指定は間違っていないのですが。
※標準のDI(Microsoft.Extensions.DependencyInjectionの時)に使えていたPMコマンドではありますが。

txt

1PM > Add-Migration init -Context TestDbContext -o "Migrations/TestDb" 2PM > Update-Database -Context TestDbContext

エラー内容

txt

1Build started... 2Build succeeded. 3Unable to create an object of type 'TestDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

(追記)PMコマンドでエラーしたので、デフォルトの引数無しコンストラクタを追加して対処しました。
PMコマンドが実行できるようになりました。

C#

1// TestDbContext 2 3using Microsoft.EntityFrameworkCore; 4using System; 5using System.Collections.Generic; 6using System.ComponentModel.DataAnnotations; 7using System.Diagnostics; 8using System.Linq; 9using System.Threading; 10using System.Threading.Tasks; 11 12namespace DomainModel { 13 public class TestDbContext : DbContext, ITestDbContext { 14 15 public TestDbContext() { 16 17 } 18 19 public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { 20 21 } 22 23 public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { 24 // ... 25 } 26 27 /// <summary> 28 /// Override OnModelCreating 29 /// </summary> 30 /// <param name="modelBuilder"></param> 31 protected override void OnModelCreating(ModelBuilder modelBuilder) { 32 // ... 33 34 base.OnModelCreating(modelBuilder); 35 } 36 37 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 38 string connectionString = "Data Source=..."; 39 40 optionsBuilder.UseSqlServer(connectionString); 41 optionsBuilder.UseLazyLoadingProxies(); 42 43 base.OnConfiguring(optionsBuilder); 44 } 45 46 public DbSet<Department> Departments { get; set; } 47 } 48}
TN8001, juner, BluOxy👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/03/24 07:04

このスレッドの課題(WPF アプリに DI 機能の実装)は下の回答で解決できたと理解していますが、そうであればこのスレッドはクローズ願います。
退会済みユーザー

退会済みユーザー

2021/03/24 12:17

DIがDrylocでDbContextを利用することが、質問の目的です。 WPFで使用しているPrismフレームワークがDrylocを使用していて、Microsoft.Extensions.DependencyInjectionは使えないようです。 MSのDIは選択肢としては良いと思いますが、どう進めるか考えてます。
退会済みユーザー

退会済みユーザー

2021/03/24 12:24

> DIがDrylocでDbContextを利用することが、質問の目的です。 了解しました・・・が、それが条件で代案は不要であれば最初の質問にその旨書き添えておいていただけたらと思います。自分も回答に余計な時間を使わずスルーできていたので。
退会済みユーザー

退会済みユーザー

2021/03/24 14:56

いえ。DIの貴重なご意見ありがとうございます。もう少しだけ質問をオープンにさせてください。
退会済みユーザー

退会済みユーザー

2021/04/06 11:59

「もう少しだけ質問をオープン」ということですがもう十分では? 放置しておかないで、自分で回答欄に何か書いてクローズできませんか。
退会済みユーザー

退会済みユーザー

2021/04/07 06:28

回答をクローズさせていただきました。
退会済みユーザー

退会済みユーザー

2021/04/08 07:52

回答を再オープンさせていただきました。
guest

回答3

0

ベストアンサー

下記リンクは今回の要件に沿うのではないでしょうか。DbContext を DI するには DbContext のインタフェースを定義する必要があります。

[C#][WPF][EF]Entity Framework で DB にアクセスする際コンテキストのオブジェクトが自動的に注入されるよう DI 機能を WPF アプリに実装したい


サービス層のプロジェクトにappsettings.jsonを置くのはどうかなと思い、悩み中です。

外からオブジェクトをもらっていきましょう。

C#

1public class TestDbContext : DbContext { 2 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 3 optionsBuilder.UseSqlServer("Data Source=tests.db"); 4 base.OnConfiguring(optionsBuilder); 5 } 6}

C#

1// App.xaml 2 3using DomainService; 4using DryIoc; 5using Prism.DryIoc; 6using Prism.Ioc; 7using System.Windows; 8using UserInterface.Views; 9 10namespace UserInterface { 11 /// <summary> 12 /// Interaction logic for App.xaml 13 /// </summary> 14 public partial class App { 15 protected override Window CreateShell() { 16 return Container.Resolve<MainWindow>(); 17 } 18 19 protected override void RegisterTypes(IContainerRegistry containerRegistry) { 20 // Drylocを利用する場合 21 var container = containerRegistry.GetContainer(); 22 container.Register<IDbContextService, DbContextService>(ifAlreadyRegistered: IfAlreadyRegistered.AppendNotKeyed); 23 container.Register<ITestDbContext, TestDbContext>(); 24 } 25 } 26}

C#

1// DbContextService 2 3using DomainModel; 4using Microsoft.EntityFrameworkCore; 5 6namespace DomainService { 7 8 public class DbContextService : IDbContextService { 9 private readonly ITestDbContext _context; 10 public DbContextService(ITestDbContext context) { 11 this._context = context; 12 } 13 } 14}

投稿2021/04/08 07:03

編集2021/04/08 10:00
BluOxy

総合スコア2663

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/04/08 07:53 編集

教えて頂いたリンクでできそうな感じです。ありがとうございます。 DbContextを隠蔽したServiceクラスとインタフェースを用意して、そのServiceクラスとインタフェースをDIするとできるようです。 一度試してみます。
退会済みユーザー

退会済みユーザー

2021/04/08 09:38 編集

教えて頂いた方法で実行することができました。ありがとうございます。 質問欄の下の方に、実行できたソースを追記させていただきました。 設定ファイルのappsettings.jsonから接続文字列を読込したかったのですが、 レイヤー単位でプロジェクトを分けているため サービス層のプロジェクトにappsettings.jsonを置くのはどうかなと思い、悩み中です。
BluOxy

2021/04/08 10:02 編集

TestDbContext のインターフェースを作ってそれを Service クラスに DI すれば良いと思います。 追記しました。
退会済みユーザー

退会済みユーザー

2021/04/08 11:38 編集

すみません、DbContextを隠蔽したDbContextServiceを作成すると勘違いしていまして、DbContextのインタフェースを作成する必要がありました。 上記に書いていませんでしたDomainModelレイヤーに、ITestDbContextとTestDbContextを準備し、DIしてみたいと思います。 実装後、再投稿させていただきます。 知識不足ですみませんが、外からオブジェクトを持ってくるのが、よく理解できませんでした。 App.xaml.csでappsettings.jsonを読込ませて利用したいのですが、読込まではできるのですが、それをDbContextに利用する方法がわかりませんでした。 ASP.NET Core MVCだと標準でserviceがついてるので、それが利用できるのですが、WPFは自前で準備しなければならないです。 教えていただいたOnConfiguringを使う方法も試してみたいと思います。
BluOxy

2021/04/08 11:40

ServiceでDbContextの実体を作るのではなく、DIコンテナ等などからDbContextの実体を注入してもらうことを外から持ってくると表現しました。
BluOxy

2021/04/08 12:01

TestDbContext.OnConfiguringの中身を下記にしたら駄目でしょうか。 EFCore を使ったことが無いので力になれず申し訳ないですが、その辺りは雰囲気で書いています。 IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) .Build(); optionsBuilder.UseSqlServer(configuration.GetConnectionString("DbConnection")); base.OnConfiguring(optionsBuilder);
退会済みユーザー

退会済みユーザー

2021/04/08 12:22 編集

OnConfiguringはnewせずに実行されるのかなと思ってますが、頂いた方法で雰囲気は似てるような感じがします。 ありがとうございます。 WPFの場合は、App.xaml.csに書くより、DbContextのOnConfiguringの方に書いたほうがいいのかな?と思いました。 App.xaml.csに書く方法ももう少し試してみたいですが、難しいかもしれません。 今日は手元に環境がないため、すみませんが、明日朝に実行してみます。
退会済みユーザー

退会済みユーザー

2021/04/09 01:19 編集

昨日質問欄のコードの追記分について、誤りがありましたので訂正させていただきました。 教えて頂いたDbContextインターフェースとOnConfiguringの方法で対応しました。 DbContextインターフェースには、DbContextに追加したメソッドは全て定義しなければいけないのかは すみませんが理解できていないです。 また、標準のDI(Microsoft.Extensions.DependencyInjectionの時)に 使えていたPMコマンドが使えなくなってしまいました。 PM > Add-Migration init -Context TestDbContext -o "Migrations/TestDb" PM > Update-Database -Context TestDbContext Build started... Build succeeded. Unable to create an object of type 'TestDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 のエラーになってしまってます。もしご存じであればご教授お願いしたく。
退会済みユーザー

退会済みユーザー

2021/04/09 02:45 編集

教えて頂いた記事を参考にし、TestDbContextにデフォルトのコンストラクタを作成するとエラーがでなくなりました。ありがとうございます。 public TestDbContext() { } 質問欄へデフォルトのコンストラクタについて追記しました。
guest

0

ASP.NET Core MVCはデフォルトのコンテナを利用しましたが、WPFアプリ(.NET 5)の場合はなかったので、Drylocを使用したいですが

「WPFアプリ(.NET 5)の場合はなかった」というのは Visual Studio のテンプレートで作ったプロジェクトには実装されてなかったということだと理解していますが、そういう場合は Microsoft.Extensions.DependencyInjection 名前空間にあるクラス類を使って自力で実装できます。

具体例は、コンソールアプリと Windows Forms の場合ですが、以下の記事を見てください。

.NET Core での Dependency Injection
http://surferonwww.info/BlogEngine/post/2021/01/01/dependency-injection-for-dotnet-core-application.aspx

Windows Forms で IHttpClientFactory 利用 (CORE)
http://surferonwww.info/BlogEngine/post/2021/03/12/how-to-use-ihttpclientfactory-in-windows-forms-application.aspx

投稿2021/03/23 04:18

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/03/23 04:37

ご回答ありがとうございます。 .NET Core での Dependency Injectionの記事を読ませて頂きます。
退会済みユーザー

退会済みユーザー

2021/03/25 00:39 編集

Microsoft.Extensions.DependencyInjection 名前空間にあるクラス類を使って自力で実装してみたところ、下記のコードでエラーが表示されなくなりました。実際に動作させて試してみたいと思います。 IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) .Build(); IServiceCollection services = new ServiceCollection(); services.AddDbContext<TestDbContext>(options => { options.UseLazyLoadingProxies(); options.UseSqlServer(configuration.GetConnectionString("DbConnection")); });
退会済みユーザー

退会済みユーザー

2021/03/23 04:58

上記のコードでコンストラクタ注入が確認できました、ありがとうございます。 Microsoft.Extensions.DependencyInjection は標準のDIなのでこれは良さそうですね。
guest

0

下記のように対応しました。

C#

1// Microsoft.Extensions.DependencyInjection の場合 2 3using DomainModel; 4using Microsoft.EntityFrameworkCore; 5using Microsoft.Extensions.Configuration; 6using Microsoft.Extensions.DependencyInjection; 7using Microsoft.Extensions.Logging; 8using System; 9using System.Configuration; 10using System.IO; 11using System.Windows; 12using UserInterface.Views; 13 14namespace UserInterface { 15 /// <summary> 16 /// Interaction logic for App.xaml 17 /// </summary> 18 public partial class App { 19 20 public IConfiguration Configuration { get; } 21 public IServiceCollection services { get; } 22 23 public App() { 24 Configuration = new ConfigurationBuilder() 25 .SetBasePath(Directory.GetCurrentDirectory()) 26 .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true) 27 .Build(); 28 29 services = new ServiceCollection(); 30 } 31 32 protected override Window CreateShell() { 33 return Container.Resolve<MainWindow>(); 34 } 35 36 protected override void RegisterTypes(IContainerRegistry containerRegistry) { 37 // Microsoft.Extensions.DependencyInjection の場合 38 services.AddDbContext<TestDbContext>(options => { 39 options.UseLazyLoadingProxies(); 40 options.UseSqlServer(Configuration.GetConnectionString("DbConnection")); 41 }); 42 } 43 } 44} 45

投稿2021/04/07 06:27

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

BluOxy

2021/04/07 10:24

今この質問に気づきました。 私はWPFのDIコンテナにPrism.Unityを使用しています。Prism.DryIocもあるので、Prismを使うという選択肢もあるということをお伝えしておきます。 https://qiita.com/nori0__/items/ba9f4c84fd3818287ad4
退会済みユーザー

退会済みユーザー

2021/04/08 06:52 編集

コメントありがとうございます。 Prism.Unity か Prism.DryIocのどちらかと使いたいと考えていました。 教えて頂いたURLの記事がとても参考になります。確認します。 もしよろしければ、PrismのDI(Unityでも大丈夫です。) の場合で、 DbContextを使う方法をご存じであれば、ご教授お願いしたいです。 自己解決は未解決に戻させて頂きました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問