是否应该通过构造函数注入存储库,或者将存储库包装在using

本文关键字:存储 或者 包装 using 构造函数 注入 是否 | 更新日期: 2023-09-27 18:09:06

使用实体框架时,将存储库注入控制器是不好的做法吗?

例如,如果我有一个服务:

public class DogService
{
    IMyDbContext _myDbContext;
    public DogService(IMyDbContext myDbContext)
    {
        _myDbContext = myDbContext;
    } 

    public void CreateDog(string name)
    {
        //create a dog using the myDbContext
    }
}

如果我们没有显式地处理存储库,那么上面的做法会是不好的吗?如果这样做会更好吗?

public void CreateDog(string name, IMyDbContext myDbContext)
{
     using(myDbContext)
     {
          //create a dog using the myDbContext
     }
}

mydbcontext:

public class MyDbContext : DbContext, IMyDbContext {}

我如何处置myDbContext?

是否应该通过构造函数注入存储库,或者将存储库包装在using

主要问题-用Dependency Injection注入DBcontext是一个好主意吗?如果是,那么它是如何处理的

是的,它可以注射,如果使用Ninject IOC,以下将有助于:

kernel.Bind<DBContext>().ToSelf().InRequestScope();

查看下面的链接,它描述了两个模式,还提供了关于如何为每个HttpRequest创建单个DBcontext的详细信息,而不管在进程中调用了多少控制器。

另一个有用的链接,如何在使用Ninject时处理DBContext

是的,您可以在使用存储库模式时注入存储库接口。我的意思是你可以使用控制器的构造函数注入它。

存储库的生存期:

所有存储库实例都是Transient。这意味着,它们在每次使用时都被实例化。因此,您不需要担心Context的处置。

下面是一个例子:这是一个存储库模式。您必须注入存储库的接口。在这个例子中,它使用了一个服务层。但是你也可以在你的控制器上做。

public class PersonAppService : IPersonAppService
{
    private readonly IRepository<Person> _personRepository;
    public PersonAppService(IRepository<Person> personRepository)
    {
        _personRepository = personRepository;
    }
    public void CreatePerson(CreatePersonInput input)
    {        
        person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };
        _personRepository.Insert(person);
    }
}

您可以在这里阅读更多信息:Repositories

你可以让DogService实现IDisposable并从DogService的Dispose方法中调用myDbContext.Dispose()

相关文章: