簡體   English   中英

C#依賴注入復制

[英]C# Dependency injection duplicating

我正在制作一個ASP.NET Core Razor Pages Web應用程序。 在我的應用程序中,使用以下代碼:

public class MyClass
{
    private readonly ApplicationDbContext _dbContext;
    private readonly ICalendarService _calendarService;

    public MyClass(ApplicationDbContext dbContext, ICalendarService calendarService)
    {
        _dbContext = dbContext;
        _calendarService = calendarService;
    }

    public void MyFunction()
    {
        // here I need to use _dbContext and _calendarService
    }

但是,當我使用此類時,我需要執行以下操作:

public class MySecondClass
{
     private ImportIntoCalendar ImportHintSchedule;
     public MySecondClass()
     {
         MyClass= new MyClass(_dbContext, _calendarService);
     }

     // Do something with variable ImportHintSchedule
     ImportHintschedule.Function()
}

每次我需要將dbcontext和calendarservice添加到參數中。 因此兩者都需要在另一個類中可用。 感覺就像我在做一些愚蠢的事情,就像我在重復相同的步驟。 有誰知道更好的方法來做到這一點。 還是這樣好嗎?

編輯:我的startup.cs中有此行

 services.AddScoped<ICalendarService, CalendarService>();

在您的ConfigureServices中,您可以添加IOC范圍。

例如,類似這樣的東西。 我不知道您的所有代碼,因此這只是一個示例。

services.AddScoped<ICalendarService, CalendarService>();
services.AddScoped<IApplicationDbContext, ApplicationDbContext>();

如果也滿足您的需求,您也可以添加單例。 這是我在應用程序中使用的單例調用示例

services.AddSingleton<IRepository<BaseItem>>(x => new Repository<BaseItem>(Configuration["MongoConnection:DefaultConnection"]));

我建議創建您的類的Interface ,例如:

public interface IMyClass {
    void MyFunction();
}

然后,在您的課程中實現它:

public class MyClass : IMyClass {

    private readonly ApplicationDbContext _dbContext;
    private readonly ICalendarService _calendarService;

    public MyClass(ApplicationDbContext dbContext, ICalendarService calendarService)
    {
        _dbContext = dbContext;
        _calendarService = calendarService;
    }

    public void MyFunction()
    {
        // here I need to use _dbContext and _calendarService
    }
 }

並將其添加到注射器:

public void ConfigureServices(IServiceCollection services)
{
    // existing code
    services.AddTransient<IMyClass, MyClass>();
}

最后在Controller構造函數中使用IMyClass

public class MyController:Controller
{
   private IMyInterface _myClass;
   public MyController(IMyInterface myclass) {
      _myClass = myClass;
   }

   public IActionResult MyAction() {
      _myClass.MyFunction();
      return View();
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM