最近私はASP.NET MVC5プロジェクトで作業しています。私は、特定のビジネスルールを複製していて、コントローラ間で共有されていることに気づいたことがあります。私は何を読んでから、ASP.NET MVCのIoC/DI、UoW、およびリポジトリパターンを使用せずにコントローラアクションから「サービスレイヤー」にロジックを移動
、asp.netのMVCにおけるmは、エンティティ、のviewmodelsやサービスからなる層であり、後者のすべての共有のビジネスロジックに
を保持している今、私のように物事を維持しようとしています可能な限り単純ですが、私はエンティティフレームワークをいくつかのUoW/Repoでラップしてそのまま使用したいとは思いませんが、このアプリケーションライフタイムでエンティティフレームワークを使用するのをやめることはほとんどありません。 IoCコンテナが必要だとは思わないが、私が読んだチュートリアルでは、IoCコンテナを使うか、UoW/Repoでdbcontext/efをラップするかのようだ。
私は、httprequestごとにDbContextのインスタンス(これは私が見たチュートリアルではIoCコンテナ経由で管理されています)が1つだけあるべきであることを読んだことがあります。コントローラのコンストラクタでインスタンス化してその参照をコントローラに必要なすべてのサービスに渡してから、要求の最後に廃棄しますか?これはdbcontextを管理する正しい方法ですか?
コントローラの例:
public class SupplierController : Controller
{
private Meerkat3Context context;
private SupplierService supplierService;
private ratingService SupplierRatingService;
public SupplierController()
{
// instantiate the dbcontext
this.context = new Meerkat3Context();
// pass dbcontext into the constructors of my services
this.supplierService = New SupplierService(context);
this.ratingService = New SupplierRatingService(context);
}
public ActionResult Index(Guid id)
{
var supplier = supplierService.getSupplier(id);
// construct viewmodel
return new SupplierIndexViewModel()
{
SupplierId = supplier.Id,
SupplierName = supplier.Name,
SupplierRating = ratingService.getHighestRating(supplier.Id),
NearbySuppliers = supplierService.getNearbySuppliers(supplier.Id),
// etc
};
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
context.Dispose();
}
base.Dispose(disposing);
}
}
サービス例:
public class SupplierService
{
private Meerkat3Context context;
public SupplierService(Meerkat3Context context)
{
this.context = context;
}
public Supplier getSupplier(Guid id)
{
return context.Where(x => x.SupplierId == id)
.FirstOrDefault()
.Select(x => new Supplier()
{
Id = x.Id,
Name = x.Name
// etc
});
}
public Supplier getNearbySuppliers(Guid id)
{
return context.Suppliers.Where(x => context.SupplierAddresses
.Where(y => y.AddressTypeId == AddressTypes.Location)
.Select(z => z.Address.TownCity)
.Contains(x.SupplierAddresses
.Where(y => y.AddressTypeId == AddressTypes.Location)
.FirstOrDefault()
.Address.TownCity)
);
}
}
public class SupplierRatingService
{
private Meerkat3Context context;
public RatingService(Meerkat3Context context)
{
this.context = context;
}
public SupplierRating getHighestRating(Guid id)
{
return context.SupplierRating
.Where(x => x.SupplierId == id)
.OrderBy(x => x.RatingValue)
.FirstOrDefault()
}
}
これは正しいです。 –
簡単にするために、VIEWModelをSQLビューと考えることができます。ここには、異なるが関連するテーブル(クラス)のさまざまなフィールドがあります。 –