【问题标题】:Dependency injection in entity classes with code first实体类中的依赖注入,代码优先
【发布时间】:2011-06-21 15:15:49
【问题描述】:

我正在尝试首先在实体框架代码中找到一种处理依赖注入的方法。

我偶然发现了一个使用 ObjectStateManager 的 article,尽管我认为它首先在代码中不可用,所以我正在寻找类似的东西,我可以将对象注入(属性注入)到新创建/获取的实体中,或者可能有不同的方式?

我使用 Autofac 作为 di 容器

【问题讨论】:

    标签: dependency-injection ef-code-first code-first


    【解决方案1】:

    你可以这样做 DI

     public class YourContext : DbContext
     {
        protected ObjectContext ObjectContext
        {
            get
            {
                return ((IObjectContextAdapter)this).ObjectContext;
            }
        }
    
        public YourContext(string connectionString):base(connectionString)
        {
            ObjectContext.ObjectMaterialized += ObjectMaterialized;
        }
    
        void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
        {
            // do property injection here using e.Entity
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-07
      • 2020-12-28
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      相关资源
      最近更新 更多