C# 工作单元和依赖注入

C# 工作单元和依赖注入,c#,asp.net-mvc,C#,Asp.net Mvc,我想在我的项目中实现工作单元设计模式,从dbContext开始,所有存储库都在UnitOfWork类中初始化,我发现这里没有地方进行依赖项注入。是否有一种使用dpendency注射的方法,或者没有必要,为什么 如果需要,可以创建DI public class UnitOfWork : IDisposable { private ISchoolContext _context; public UnitOfWork(ISchoolContext context) {

我想在我的项目中实现工作单元设计模式,从dbContext开始,所有存储库都在UnitOfWork类中初始化,我发现这里没有地方进行依赖项注入。是否有一种使用dpendency注射的方法,或者没有必要,为什么

如果需要,可以创建DI

public class UnitOfWork : IDisposable
{
    private ISchoolContext _context;

    public UnitOfWork(ISchoolContext context) 
    {
        _context = context;
    }    
}
然后在控制器中,您也可以以相同的方式注入工作单元


你可以做所有这些事情,现在的问题是,你是否需要那种奇特的DI,我个人会的,但这取决于你和你的需要。

如果你愿意,你可以创建DI

public class UnitOfWork : IDisposable
{
    private ISchoolContext _context;

    public UnitOfWork(ISchoolContext context) 
    {
        _context = context;
    }    
}
然后在控制器中,您也可以以相同的方式注入工作单元


您可以做所有这些事情,现在的问题是您是否需要这种奇特的DI,我个人会这样做,但这取决于您和您的需要。

以下是使用DbContext时工作单元的实现:

class UnitOfWork : IDisposable
{
   private readonly DbContext _yourDbContext; 

   public UnitOfWork(DbContext yourDbContext)
   {
      _yourDbContext = yourDbContext
   }

   public void Save()
   {
       _yourDbContext.Save();      
   }

   void Dispose()
   {       
       _yourDbContext = null;   
   }
}

public interface IUnitOfWork
{
    void Save();    
}

用途:

IUnitOfWork _uow;

_yourStudentRepository.Add(Student);
_yourAddressRepository.Add(Address);
_uow.Save();

以下是使用DbContext时工作单元的实现:

class UnitOfWork : IDisposable
{
   private readonly DbContext _yourDbContext; 

   public UnitOfWork(DbContext yourDbContext)
   {
      _yourDbContext = yourDbContext
   }

   public void Save()
   {
       _yourDbContext.Save();      
   }

   void Dispose()
   {       
       _yourDbContext = null;   
   }
}

public interface IUnitOfWork
{
    void Save();    
}

用途:

IUnitOfWork _uow;

_yourStudentRepository.Add(Student);
_yourAddressRepository.Add(Address);
_uow.Save();

而不是私立学校的背景(u context);;它应该是私有的ISchoolContext\u上下文;而不是私立学校的背景(u context);;它应该是私有的ISchoolContext\u上下文;如果您将使用实体框架,那么您可以跳过UnitOfWork和存储库。我用这种方法已经有一段时间了,效果很好:@scgough谢谢,我担心这种方法会不会很好,或者我会有很多问题。如果你要使用实体框架,那么你可以跳过
UnitOfWork
和存储库。嗨-请看我对UoW/通用存储库的回答。我用这种方法已经有一段时间了,效果非常好:@scgough谢谢,我担心这种方法会不会奏效,或者我会遇到很多问题。