【问题标题】:ASP.NET BoilerPlate: How do I inject object of DbContext in application service?ASP.NET BoilerPlate:如何在应用程序服务中注入 DbContext 对象?
【发布时间】:2017-07-08 13:40:22
【问题描述】:

如何在应用服务中注入 DbContext 对象?

需要访问它以创建实体记录的克隆。

【问题讨论】:

    标签: c# asp.net aspnetboilerplate


    【解决方案1】:

    你可以使用IDbContextProvider<TDbContext> _sampleDbContextProvider作为构造函数注入,与_sampleDbContextProvider.GetDbContext();一起使用

    【讨论】:

    • 我使用你的答案,但我在 _sampleDbContextProvider 中总是为空
    【解决方案2】:

    克隆实体的一个棘手方法是序列化然后反序列化对象。使用Newtonsoft 进行序列化。 只需此代码即可使用

    MyEntity myEntity = _myEntityRepository.get(1);
    string cloned = JsonConvert.SerializeObject(myEntity);
    MyEntity clonedEntity = JsonConvert.DeserializeObject<MyEntity>(cloned);
    clonedEntity.Id = 0;
    

    【讨论】:

      【解决方案3】:

      这个问题有点模棱两可,但这里有几件事供您考虑:

      依赖注入:AUTOFAC 或 NINJECT(例如) 这将允许您通过 ctor 或属性将您的 DbContext 注入到任何类中,以便您可以使用它。

      将其作为参数传递(您的服务是如何生成的?)

      var appService = new ApplicationService(new MyDbContext())

      其中任何一个都可以。如果这不是你的意思,更多信息会有所帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多